<!DOCTYPE HTML>
<html lang="zh-CN">


<head>
    <meta charset="utf-8">
    <meta name="keywords" content="简单了解清华大学朱军珠算框架, SongX64">
    <meta name="description" content="">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=no">
    <meta name="renderer" content="webkit|ie-stand|ie-comp">
    <meta name="mobile-web-app-capable" content="yes">
    <meta name="format-detection" content="telephone=no">
    <meta name="apple-mobile-web-app-capable" content="yes">
    <meta name="baidu-site-verification" content="code-8GV6uhDsco" />
    <meta name="apple-mobile-web-app-status-bar-style" content="black-translucent">
    <!-- Global site tag (gtag.js) - Google Analytics -->


    <title>简单了解清华大学朱军珠算框架 | SongX64</title>
    <link rel="icon" type="image/png" href="/favicon.png">

    <link rel="stylesheet" type="text/css" href="/libs/awesome/css/all.css">
    <link rel="stylesheet" type="text/css" href="/libs/materialize/materialize.min.css">
    <link rel="stylesheet" type="text/css" href="/libs/aos/aos.css">
    <link rel="stylesheet" type="text/css" href="/libs/animate/animate.min.css">
    <link rel="stylesheet" type="text/css" href="/libs/lightGallery/css/lightgallery.min.css">
    <link rel="stylesheet" type="text/css" href="/css/matery.css">
    <link rel="stylesheet" type="text/css" href="/css/my.css">

    <script src="/libs/jquery/jquery.min.js"></script>

<meta name="generator" content="Hexo 5.4.0"><link rel="alternate" href="/atom.xml" title="SongX64" type="application/atom+xml">
</head>



   <style>
    body{
       background-image: url(https://gitee.com/songx86/SongPicBed/raw/master/img/fd039245d688d43f5595595b7d1ed21b0ef43b5f.jpg);
       background-repeat:no-repeat;
       background-size:cover;
       background-attachment:fixed;
    }
</style>



<body>
    <header class="navbar-fixed">
    <nav id="headNav" class="bg-color nav-transparent">
        <div id="navContainer" class="nav-wrapper container">
            <div class="brand-logo">
                <a href="/" class="waves-effect waves-light">
                    
                    <img src="/medias/logo.png" class="logo-img" alt="LOGO">
                    
                    <span class="logo-span">SongX64</span>
                </a>
            </div>
            

<a href="#" data-target="mobile-nav" class="sidenav-trigger button-collapse"><i class="fas fa-bars"></i></a>
<ul class="right nav-menu">
  
  <li class="hide-on-med-and-down nav-item">
    
    <a href="/" class="waves-effect waves-light">
      
      <i class="fas fa-home" style="zoom: 0.6;"></i>
      
      <span>首页</span>
    </a>
    
  </li>
  
  <li class="hide-on-med-and-down nav-item">
    
    <a href="/tags" class="waves-effect waves-light">
      
      <i class="fas fa-tags" style="zoom: 0.6;"></i>
      
      <span>标签</span>
    </a>
    
  </li>
  
  <li class="hide-on-med-and-down nav-item">
    
    <a href="/categories" class="waves-effect waves-light">
      
      <i class="fas fa-bookmark" style="zoom: 0.6;"></i>
      
      <span>分类</span>
    </a>
    
  </li>
  
  <li class="hide-on-med-and-down nav-item">
    
    <a href="/archives" class="waves-effect waves-light">
      
      <i class="fas fa-archive" style="zoom: 0.6;"></i>
      
      <span>归档</span>
    </a>
    
  </li>
  
  <li class="hide-on-med-and-down nav-item">
    
    <a href="/about" class="waves-effect waves-light">
      
      <i class="fas fa-user-circle" style="zoom: 0.6;"></i>
      
      <span>关于</span>
    </a>
    
  </li>
  
  <li class="hide-on-med-and-down nav-item">
    
    <a href="/contact" class="waves-effect waves-light">
      
      <i class="fas fa-comments" style="zoom: 0.6;"></i>
      
      <span>留言板</span>
    </a>
    
  </li>
  
  <li class="hide-on-med-and-down nav-item">
    
    <a href="/friends" class="waves-effect waves-light">
      
      <i class="fas fa-address-book" style="zoom: 0.6;"></i>
      
      <span>友情链接</span>
    </a>
    
  </li>
  
  <li>
    <a href="#searchModal" class="modal-trigger waves-effect waves-light">
      <i id="searchIcon" class="fas fa-search" title="搜索" style="zoom: 0.85;"></i>
    </a>
  </li>
</ul>


<div id="mobile-nav" class="side-nav sidenav">

    <div class="mobile-head bg-color">
        
        <img src="/medias/logo.png" class="logo-img circle responsive-img">
        
        <div class="logo-name">SongX64</div>
        <div class="logo-desc">
            
            Never really desperate, only the lost of the soul.
            
        </div>
    </div>

    

    <ul class="menu-list mobile-menu-list">
        
        <li class="m-nav-item">
	  
		<a href="/" class="waves-effect waves-light">
			
			    <i class="fa-fw fas fa-home"></i>
			
			首页
		</a>
          
        </li>
        
        <li class="m-nav-item">
	  
		<a href="/tags" class="waves-effect waves-light">
			
			    <i class="fa-fw fas fa-tags"></i>
			
			标签
		</a>
          
        </li>
        
        <li class="m-nav-item">
	  
		<a href="/categories" class="waves-effect waves-light">
			
			    <i class="fa-fw fas fa-bookmark"></i>
			
			分类
		</a>
          
        </li>
        
        <li class="m-nav-item">
	  
		<a href="/archives" class="waves-effect waves-light">
			
			    <i class="fa-fw fas fa-archive"></i>
			
			归档
		</a>
          
        </li>
        
        <li class="m-nav-item">
	  
		<a href="/about" class="waves-effect waves-light">
			
			    <i class="fa-fw fas fa-user-circle"></i>
			
			关于
		</a>
          
        </li>
        
        <li class="m-nav-item">
	  
		<a href="/contact" class="waves-effect waves-light">
			
			    <i class="fa-fw fas fa-comments"></i>
			
			留言板
		</a>
          
        </li>
        
        <li class="m-nav-item">
	  
		<a href="/friends" class="waves-effect waves-light">
			
			    <i class="fa-fw fas fa-address-book"></i>
			
			友情链接
		</a>
          
        </li>
        
        
        <li><div class="divider"></div></li>
        <li>
            <a href="https://github.com/blinkfox/hexo-theme-matery" class="waves-effect waves-light" target="_blank">
                <i class="fab fa-github-square fa-fw"></i>Fork Me
            </a>
        </li>
        
    </ul>
</div>


        </div>

        
            <style>
    .nav-transparent .github-corner {
        display: none !important;
    }

    .github-corner {
        position: absolute;
        z-index: 10;
        top: 0;
        right: 0;
        border: 0;
        transform: scale(1.1);
    }

    .github-corner svg {
        color: #0f9d58;
        fill: #fff;
        height: 64px;
        width: 64px;
    }

    .github-corner:hover .octo-arm {
        animation: a 0.56s ease-in-out;
    }

    .github-corner .octo-arm {
        animation: none;
    }

    @keyframes a {
        0%,
        to {
            transform: rotate(0);
        }
        20%,
        60% {
            transform: rotate(-25deg);
        }
        40%,
        80% {
            transform: rotate(10deg);
        }
    }
</style>

<a href="https://github.com/blinkfox/hexo-theme-matery" class="github-corner tooltipped hide-on-med-and-down" target="_blank"
   data-tooltip="Fork Me" data-position="left" data-delay="50">
    <svg viewBox="0 0 250 250" aria-hidden="true">
        <path d="M0,0 L115,115 L130,115 L142,142 L250,250 L250,0 Z"></path>
        <path d="M128.3,109.0 C113.8,99.7 119.0,89.6 119.0,89.6 C122.0,82.7 120.5,78.6 120.5,78.6 C119.2,72.0 123.4,76.3 123.4,76.3 C127.3,80.9 125.5,87.3 125.5,87.3 C122.9,97.6 130.6,101.9 134.4,103.2"
              fill="currentColor" style="transform-origin: 130px 106px;" class="octo-arm"></path>
        <path d="M115.0,115.0 C114.9,115.1 118.7,116.5 119.8,115.4 L133.7,101.6 C136.9,99.2 139.9,98.4 142.2,98.6 C133.8,88.0 127.5,74.4 143.8,58.0 C148.5,53.4 154.0,51.2 159.7,51.0 C160.3,49.4 163.2,43.6 171.4,40.1 C171.4,40.1 176.1,42.5 178.8,56.2 C183.1,58.6 187.2,61.8 190.9,65.4 C194.5,69.0 197.7,73.2 200.1,77.6 C213.8,80.2 216.3,84.9 216.3,84.9 C212.7,93.1 206.9,96.0 205.4,96.6 C205.1,102.4 203.0,107.8 198.3,112.5 C181.9,128.9 168.3,122.5 157.7,114.1 C157.9,116.9 156.7,120.9 152.7,124.9 L141.0,136.5 C139.8,137.7 141.6,141.9 141.8,141.8 Z"
              fill="currentColor" class="octo-body"></path>
    </svg>
</a>
        
    </nav>

</header>

    



<div class="bg-cover pd-header post-cover" style="background-image: url('/medias/featureimages/1/02.jpg')">
    <div class="container" style="right: 0px;left: 0px;">
        <div class="row">
            <div class="col s12 m12 l12">
                <div class="brand">
                    <h1 class="description center-align post-title">简单了解清华大学朱军珠算框架</h1>
                </div>
            </div>
        </div>
    </div>
</div>




<main class="post-container content">

    
    <link rel="stylesheet" href="/libs/tocbot/tocbot.css">
<style>
    #articleContent h1::before,
    #articleContent h2::before,
    #articleContent h3::before,
    #articleContent h4::before,
    #articleContent h5::before,
    #articleContent h6::before {
        display: block;
        content: " ";
        height: 100px;
        margin-top: -100px;
        visibility: hidden;
    }

    #articleContent :focus {
        outline: none;
    }

    .toc-fixed {
        position: fixed;
        top: 64px;
    }

    .toc-widget {
        width: 345px;
        padding-left: 20px;
    }

    .toc-widget .toc-title {
        padding: 35px 0 15px 17px;
        font-size: 1.5rem;
        font-weight: bold;
        line-height: 1.5rem;
    }

    .toc-widget ol {
        padding: 0;
        list-style: none;
    }

    #toc-content {
        padding-bottom: 30px;
        overflow: auto;
    }

    #toc-content ol {
        padding-left: 10px;
    }

    #toc-content ol li {
        padding-left: 10px;
    }

    #toc-content .toc-link:hover {
        color: #42b983;
        font-weight: 700;
        text-decoration: underline;
    }

    #toc-content .toc-link::before {
        background-color: transparent;
        max-height: 25px;

        position: absolute;
        right: 23.5vw;
        display: block;
    }

    #toc-content .is-active-link {
        color: #42b983;
    }

    #floating-toc-btn {
        position: fixed;
        right: 15px;
        bottom: 76px;
        padding-top: 15px;
        margin-bottom: 0;
        z-index: 998;
    }

    #floating-toc-btn .btn-floating {
        width: 48px;
        height: 48px;
    }

    #floating-toc-btn .btn-floating i {
        line-height: 48px;
        font-size: 1.4rem;
    }
</style>
<div class="row">
    <div id="main-content" class="col s12 m12 l9">
        <!-- 文章内容详情 -->
<div id="artDetail">
    <div class="card">
        <div class="card-content article-info">
            <div class="row tag-cate">
                <div class="col s7">
                    
                    <div class="article-tag">
                        
                            <a href="/tags/%E7%A7%91%E7%A0%94/">
                                <span class="chip bg-color">科研</span>
                            </a>
                        
                            <a href="/tags/%E7%8F%A0%E7%AE%97/">
                                <span class="chip bg-color">珠算</span>
                            </a>
                        
                    </div>
                    
                </div>
                <div class="col s5 right-align">
                    
                    <div class="post-cate">
                        <i class="fas fa-bookmark fa-fw icon-category"></i>
                        
                            <a href="/categories/%E7%A7%91%E7%A0%94/" class="post-category">
                                科研
                            </a>
                        
                    </div>
                    
                </div>
            </div>

            <div class="post-info">
                
                <div class="post-date info-break-policy">
                    <i class="far fa-calendar-minus fa-fw"></i>发布日期:&nbsp;&nbsp;
                    2020-02-19
                </div>
                

                

                
                <div class="info-break-policy">
                    <i class="far fa-file-word fa-fw"></i>文章字数:&nbsp;&nbsp;
                    5.7k
                </div>
                

                
                <div class="info-break-policy">
                    <i class="far fa-clock fa-fw"></i>阅读时长:&nbsp;&nbsp;
                    22 分
                </div>
                

                
            </div>
        </div>
        <hr class="clearfix">

        
        <!-- 是否加载使用自带的 prismjs. -->
        <link rel="stylesheet" href="/libs/prism/prism.css">
        

        

        <div class="card-content article-card-content">
            <div id="articleContent">
                <h1 id="珠算的基本概念"><a href="#珠算的基本概念" class="headerlink" title="珠算的基本概念"></a>珠算的基本概念</h1><h3 id="补充：张量"><a href="#补充：张量" class="headerlink" title="补充：张量"></a>补充：张量</h3><p><img src="https://pic1.zhimg.com/80/v2-c90867d134da775194ee98a97def9ea4_hd.jpg" alt="何为张量"></p>
<p>如图所示，0维就是数，1维是向量，2维是矩阵，3维以上就是张量了。当然一个1维向量也可叫做1维张量。</p>
<h2 id="分布"><a href="#分布" class="headerlink" title="分布"></a>分布</h2><blockquote>
<h2 id="分布-1"><a href="#分布-1" class="headerlink" title="分布"></a>分布</h2><p>分布是构建概率模型的基本功能。  Distribution类是各种概率分布的基类，它支持批输入，生成批量样本并评估给定值批次的概率。</p>
<p>可用的分布：</p>
<p><a target="_blank" rel="noopener" href="https://zhusuan.readthedocs.io/en/latest/api/zhusuan.distributions.html#module-zhusuan.distributions.univariate">单变量分布</a></p>
<p><a target="_blank" rel="noopener" href="https://zhusuan.readthedocs.io/en/latest/api/zhusuan.distributions.html#module-zhusuan.distributions.multivariate">多变量分布</a></p>
<p>我们可用珠算来创建一个<strong>单变量正态分布</strong>，代码如下：</p>
<pre class="line-numbers language-python" data-language="python"><code class="language-python"><span class="token operator">>></span><span class="token operator">></span> <span class="token keyword">import</span> zhusuan <span class="token keyword">as</span> zs
<span class="token operator">>></span><span class="token operator">></span> a <span class="token operator">=</span> zs<span class="token punctuation">.</span>distributions<span class="token punctuation">.</span>Normal<span class="token punctuation">(</span>mean<span class="token operator">=</span><span class="token number">0</span><span class="token punctuation">.</span><span class="token punctuation">,</span> logstd<span class="token operator">=</span><span class="token number">0</span><span class="token punctuation">.</span><span class="token punctuation">)</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span></span></code></pre>

<p>分布典型的输入形状是像<code>batch_shape + input_shape</code>，其中<code>batch_shape</code>表示一个non-batch的输入参数的形状;<code>batch_shape</code>代表有多少个独立的输入变量被放到分布中。总的来说，分布支持boradcast的输入。</p>
</blockquote>
<hr>
<h3 id="补充：boradcast机制"><a href="#补充：boradcast机制" class="headerlink" title="补充：boradcast机制"></a>补充：boradcast机制</h3><p>boradcast机制是numpy中的机制。TensorFlow中好像叫boradcasting机制……应该差不多吧。TensorFlow有不少操作支持boradcast。</p>
<p>举例如下：</p>
<pre class="line-numbers language-python" data-language="python"><code class="language-python"><span class="token operator">>></span><span class="token operator">></span> <span class="token keyword">import</span> numpy <span class="token keyword">as</span> np
<span class="token operator">>></span><span class="token operator">></span> a <span class="token operator">=</span> np<span class="token punctuation">.</span>arange<span class="token punctuation">(</span><span class="token number">0</span><span class="token punctuation">,</span> <span class="token number">6</span><span class="token punctuation">)</span><span class="token punctuation">.</span>reshape<span class="token punctuation">(</span><span class="token number">6</span><span class="token punctuation">,</span> <span class="token number">1</span><span class="token punctuation">)</span>
<span class="token operator">>></span><span class="token operator">></span> a
array<span class="token punctuation">(</span><span class="token punctuation">[</span><span class="token punctuation">[</span> <span class="token number">0</span><span class="token punctuation">]</span><span class="token punctuation">,</span> <span class="token punctuation">[</span><span class="token number">1</span><span class="token punctuation">]</span><span class="token punctuation">,</span> <span class="token punctuation">[</span><span class="token number">2</span><span class="token punctuation">]</span><span class="token punctuation">,</span> <span class="token punctuation">[</span><span class="token number">3</span><span class="token punctuation">]</span><span class="token punctuation">,</span> <span class="token punctuation">[</span><span class="token number">4</span><span class="token punctuation">]</span><span class="token punctuation">,</span> <span class="token punctuation">[</span><span class="token number">5</span><span class="token punctuation">]</span><span class="token punctuation">]</span><span class="token punctuation">)</span>
<span class="token operator">>></span><span class="token operator">></span> a<span class="token punctuation">.</span>shape
<span class="token punctuation">(</span><span class="token number">6</span><span class="token punctuation">,</span> <span class="token number">1</span><span class="token punctuation">)</span>
<span class="token operator">>></span><span class="token operator">></span> b <span class="token operator">=</span> np<span class="token punctuation">.</span>arange<span class="token punctuation">(</span><span class="token number">0</span><span class="token punctuation">,</span> <span class="token number">5</span><span class="token punctuation">)</span>
<span class="token operator">>></span><span class="token operator">></span> b<span class="token punctuation">.</span>shape
<span class="token punctuation">(</span><span class="token number">5</span><span class="token punctuation">,</span><span class="token punctuation">)</span>
<span class="token operator">>></span><span class="token operator">></span> c <span class="token operator">=</span> a <span class="token operator">+</span> b
<span class="token operator">>></span><span class="token operator">></span> <span class="token keyword">print</span> c
<span class="token punctuation">[</span><span class="token punctuation">[</span><span class="token number">0</span> <span class="token number">1</span> <span class="token number">2</span> <span class="token number">3</span> <span class="token number">4</span><span class="token punctuation">]</span>
 <span class="token punctuation">[</span><span class="token number">1</span> <span class="token number">2</span> <span class="token number">3</span> <span class="token number">4</span> <span class="token number">5</span><span class="token punctuation">]</span>
 <span class="token punctuation">[</span><span class="token number">2</span> <span class="token number">3</span> <span class="token number">4</span> <span class="token number">5</span> <span class="token number">6</span><span class="token punctuation">]</span>
 <span class="token punctuation">[</span><span class="token number">3</span> <span class="token number">4</span> <span class="token number">5</span> <span class="token number">6</span> <span class="token number">7</span><span class="token punctuation">]</span>
 <span class="token punctuation">[</span><span class="token number">4</span> <span class="token number">5</span> <span class="token number">6</span> <span class="token number">7</span> <span class="token number">8</span><span class="token punctuation">]</span>
 <span class="token punctuation">[</span><span class="token number">5</span> <span class="token number">6</span> <span class="token number">7</span> <span class="token number">8</span> <span class="token number">9</span><span class="token punctuation">]</span><span class="token punctuation">]</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>

<p>图解：</p>
<p><img src="https://gitee.com/songx86/SongPicBed/raw/master/img/1570782921386.png" alt="1570764082789"></p>
<p>不同维度向量相加，可以自动填充。</p>
<p>官方示例图：</p>
<p><img src="https://gitee.com/songx86/SongPicBed/raw/master/img/1570764082789.png" alt="1570764298600"></p>
<p>更全的一个图：（矩阵+矩阵，矩阵+向量，向量+向量）</p>
<p><img src="https://gitee.com/songx86/SongPicBed/raw/master/img/1570764298600.png" alt="1570764825003"></p>
<p>广播机制的规则：</p>
<ol>
<li><p>让所有输入数组都向其中shape最长的数组看齐，shape中不足的部分都通过在前面加1补齐</p>
<p>（这是是说shape+1,矩阵中数据是复制的)</p>
</li>
<li><p>输出数组的shape是输入数组shape的各个轴上的最大值</p>
<p>（例如上面的5和6）</p>
</li>
<li><p>如果输入数组的某个轴和输出数组的对应轴的长度相同或者其长度为1时，这个数组能够用来计算，否则出错</p>
<p>（如果有多行的话就不知道复制哪一行了，所以说要求是1）</p>
</li>
<li><p>当输入数组的某个轴的长度为1时，沿着此轴运算时都用此轴上的第一组值</p>
<p>（复制第一行）</p>
</li>
</ol>
<p><a target="_blank" rel="noopener" href="https://blog.csdn.net/yangnanhai93/article/details/50127747">TensorFlow, numpy中的broadcast机制</a></p>
<hr>
<blockquote>
<p>可以通过调用<code>distribution</code>对象的<code>sample()</code>方法来创建例子。它的形状是<code>([n_samples] + )batch_shape + value_shape</code>。只有当传递的n_samples为None(默认情况下)时，才会省略第一个附加<strong>轴</strong>.，在这种情况下创建一个样本。<code>value_shape</code>是非批次输入值的分布的形状。对于一个单变量分布来说，它的<code>value_shape</code>是<code>[]</code>。</p>
</blockquote>
<hr>
<h3 id="补充：axis参数"><a href="#补充：axis参数" class="headerlink" title="补充：axis参数"></a>补充：axis参数</h3><p>axis是许多函数中都有的一个参数，直接翻译是轴。其实是对于张量来说的一个概念。如下：</p>
<pre class="line-numbers language-python" data-language="python"><code class="language-python"><span class="token comment">#python</span>
x<span class="token operator">=</span><span class="token punctuation">[</span><span class="token punctuation">[</span><span class="token number">1</span><span class="token punctuation">,</span><span class="token number">2</span><span class="token punctuation">]</span><span class="token punctuation">,</span><span class="token punctuation">[</span><span class="token number">5</span><span class="token punctuation">,</span><span class="token number">1</span><span class="token punctuation">]</span><span class="token punctuation">]</span>
x<span class="token operator">=</span>np<span class="token punctuation">.</span>array<span class="token punctuation">(</span>x<span class="token punctuation">)</span>
z1<span class="token operator">=</span>np<span class="token punctuation">.</span><span class="token builtin">max</span><span class="token punctuation">(</span>x<span class="token punctuation">,</span>axis<span class="token operator">=</span><span class="token number">0</span><span class="token punctuation">)</span>
z2<span class="token operator">=</span>np<span class="token punctuation">.</span><span class="token builtin">max</span><span class="token punctuation">(</span>x<span class="token punctuation">,</span>axis<span class="token operator">=</span><span class="token number">1</span><span class="token punctuation">)</span>


<span class="token comment">#tensorflow</span>
x<span class="token operator">=</span>tf<span class="token punctuation">.</span>constant<span class="token punctuation">(</span><span class="token punctuation">[</span><span class="token punctuation">[</span><span class="token number">1</span><span class="token punctuation">.</span><span class="token punctuation">,</span><span class="token number">2</span><span class="token punctuation">.</span><span class="token punctuation">]</span><span class="token punctuation">,</span><span class="token punctuation">[</span><span class="token number">5</span><span class="token punctuation">.</span><span class="token punctuation">,</span><span class="token number">2</span><span class="token punctuation">.</span><span class="token punctuation">]</span><span class="token punctuation">]</span><span class="token punctuation">)</span>  
x<span class="token operator">=</span>tf<span class="token punctuation">.</span>shape<span class="token punctuation">(</span>x<span class="token punctuation">)</span>  
z1<span class="token operator">=</span>tf<span class="token punctuation">.</span>reduce_max<span class="token punctuation">(</span>x<span class="token punctuation">,</span>axis<span class="token operator">=</span><span class="token number">0</span><span class="token punctuation">)</span><span class="token comment">#沿axis=0操作  </span>
z2<span class="token operator">=</span>tf<span class="token punctuation">.</span>reduce_max<span class="token punctuation">(</span>x<span class="token punctuation">,</span>axis<span class="token operator">=</span><span class="token number">1</span><span class="token punctuation">)</span><span class="token comment">#沿axis=1操作</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>

<p>​    类似的还有argmax，sum等等函数，它们都含有一个名为axis的参数，那这个参数到底是什么意思呢？一句话总结就是：沿着axis指定的轴进行相应的函数操作。</p>
<p>​    对于2维来说，axis=0就是列，axis就是行，这里不再详解。直接理解3维的。</p>
<pre class="line-numbers language-python" data-language="python"><code class="language-python"><span class="token operator">>></span><span class="token operator">></span> z
array<span class="token punctuation">(</span><span class="token punctuation">[</span><span class="token punctuation">[</span><span class="token punctuation">[</span> <span class="token number">2</span><span class="token punctuation">,</span>  <span class="token number">3</span><span class="token punctuation">,</span>  <span class="token number">4</span><span class="token punctuation">,</span>  <span class="token number">8</span><span class="token punctuation">]</span><span class="token punctuation">,</span>
        <span class="token punctuation">[</span> <span class="token number">3</span><span class="token punctuation">,</span>  <span class="token number">1</span><span class="token punctuation">,</span>  <span class="token number">4</span><span class="token punctuation">,</span>  <span class="token number">1</span><span class="token punctuation">]</span><span class="token punctuation">,</span>
        <span class="token punctuation">[</span> <span class="token number">6</span><span class="token punctuation">,</span>  <span class="token number">3</span><span class="token punctuation">,</span>  <span class="token number">2</span><span class="token punctuation">,</span>  <span class="token number">6</span><span class="token punctuation">]</span><span class="token punctuation">]</span><span class="token punctuation">,</span>

       <span class="token punctuation">[</span><span class="token punctuation">[</span><span class="token number">10</span><span class="token punctuation">,</span>  <span class="token number">2</span><span class="token punctuation">,</span> <span class="token number">45</span><span class="token punctuation">,</span>  <span class="token number">2</span><span class="token punctuation">]</span><span class="token punctuation">,</span>
        <span class="token punctuation">[</span> <span class="token number">2</span><span class="token punctuation">,</span>  <span class="token number">4</span><span class="token punctuation">,</span>  <span class="token number">5</span><span class="token punctuation">,</span> <span class="token number">10</span><span class="token punctuation">]</span><span class="token punctuation">,</span>
        <span class="token punctuation">[</span><span class="token number">22</span><span class="token punctuation">,</span>  <span class="token number">4</span><span class="token punctuation">,</span>  <span class="token number">4</span><span class="token punctuation">,</span>  <span class="token number">1</span><span class="token punctuation">]</span><span class="token punctuation">]</span><span class="token punctuation">]</span><span class="token punctuation">)</span>
<span class="token operator">>></span><span class="token operator">></span> z<span class="token punctuation">.</span>shape
<span class="token punctuation">(</span><span class="token number">2</span><span class="token punctuation">,</span> <span class="token number">3</span><span class="token punctuation">,</span> <span class="token number">4</span><span class="token punctuation">)</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>

<p>​    这是一个2x3x4的3维张量，或者直接说是三维数组。</p>
<p>​    接下来我们看一下max()为例，取不同axis的形状：</p>
<pre class="line-numbers language-python" data-language="python"><code class="language-python"><span class="token operator">>></span><span class="token operator">></span> np<span class="token punctuation">.</span><span class="token builtin">max</span><span class="token punctuation">(</span>z<span class="token punctuation">,</span>axis<span class="token operator">=</span><span class="token number">0</span><span class="token punctuation">)</span><span class="token punctuation">.</span>shape
<span class="token punctuation">(</span><span class="token number">3</span><span class="token punctuation">,</span> <span class="token number">4</span><span class="token punctuation">)</span>
<span class="token operator">>></span><span class="token operator">></span> np<span class="token punctuation">.</span><span class="token builtin">max</span><span class="token punctuation">(</span>z<span class="token punctuation">,</span>axis<span class="token operator">=</span><span class="token number">1</span><span class="token punctuation">)</span><span class="token punctuation">.</span>shape
<span class="token punctuation">(</span><span class="token number">2</span><span class="token punctuation">,</span> <span class="token number">4</span><span class="token punctuation">)</span>
<span class="token operator">>></span><span class="token operator">></span> np<span class="token punctuation">.</span><span class="token builtin">max</span><span class="token punctuation">(</span>z<span class="token punctuation">,</span>axis<span class="token operator">=</span><span class="token number">2</span><span class="token punctuation">)</span><span class="token punctuation">.</span>shape
<span class="token punctuation">(</span><span class="token number">2</span><span class="token punctuation">,</span> <span class="token number">3</span><span class="token punctuation">)</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>

<p>​    也就是说，axis取几，就去掉那个维度。这里的<strong>axis是对应shape中的第几个数，也就是第几维。</strong>比如axis=0就是说(2,3,4)中的2; axis=1就是对应3……以此类推。</p>
<p>​    其计算的最后输出结果如下：</p>
<pre class="line-numbers language-python" data-language="python"><code class="language-python"><span class="token operator">>></span><span class="token operator">></span> np<span class="token punctuation">.</span><span class="token builtin">max</span><span class="token punctuation">(</span>z<span class="token punctuation">,</span>axis<span class="token operator">=</span><span class="token number">0</span><span class="token punctuation">)</span>
array<span class="token punctuation">(</span><span class="token punctuation">[</span><span class="token punctuation">[</span><span class="token number">10</span><span class="token punctuation">,</span>  <span class="token number">3</span><span class="token punctuation">,</span> <span class="token number">45</span><span class="token punctuation">,</span>  <span class="token number">8</span><span class="token punctuation">]</span><span class="token punctuation">,</span>
       <span class="token punctuation">[</span> <span class="token number">3</span><span class="token punctuation">,</span>  <span class="token number">4</span><span class="token punctuation">,</span>  <span class="token number">5</span><span class="token punctuation">,</span> <span class="token number">10</span><span class="token punctuation">]</span><span class="token punctuation">,</span>
       <span class="token punctuation">[</span><span class="token number">22</span><span class="token punctuation">,</span>  <span class="token number">4</span><span class="token punctuation">,</span>  <span class="token number">4</span><span class="token punctuation">,</span>  <span class="token number">6</span><span class="token punctuation">]</span><span class="token punctuation">]</span><span class="token punctuation">)</span>
<span class="token operator">>></span><span class="token operator">></span> np<span class="token punctuation">.</span><span class="token builtin">max</span><span class="token punctuation">(</span>z<span class="token punctuation">,</span>axis<span class="token operator">=</span><span class="token number">1</span><span class="token punctuation">)</span>
array<span class="token punctuation">(</span><span class="token punctuation">[</span><span class="token punctuation">[</span> <span class="token number">6</span><span class="token punctuation">,</span>  <span class="token number">3</span><span class="token punctuation">,</span>  <span class="token number">4</span><span class="token punctuation">,</span>  <span class="token number">8</span><span class="token punctuation">]</span><span class="token punctuation">,</span>
       <span class="token punctuation">[</span><span class="token number">22</span><span class="token punctuation">,</span>  <span class="token number">4</span><span class="token punctuation">,</span> <span class="token number">45</span><span class="token punctuation">,</span> <span class="token number">10</span><span class="token punctuation">]</span><span class="token punctuation">]</span><span class="token punctuation">)</span>
<span class="token operator">>></span><span class="token operator">></span> np<span class="token punctuation">.</span><span class="token builtin">max</span><span class="token punctuation">(</span>z<span class="token punctuation">,</span>axis<span class="token operator">=</span><span class="token number">2</span><span class="token punctuation">)</span>
array<span class="token punctuation">(</span><span class="token punctuation">[</span><span class="token punctuation">[</span> <span class="token number">8</span><span class="token punctuation">,</span>  <span class="token number">4</span><span class="token punctuation">,</span>  <span class="token number">6</span><span class="token punctuation">]</span><span class="token punctuation">,</span>
       <span class="token punctuation">[</span><span class="token number">45</span><span class="token punctuation">,</span> <span class="token number">10</span><span class="token punctuation">,</span> <span class="token number">22</span><span class="token punctuation">]</span><span class="token punctuation">]</span><span class="token punctuation">)</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>

<p>​    解释一下，比如axis=0，那么它的输出就是去掉第一维度的影响，也就是(2,3,4)中去掉2，应该是个(3,4)的张量，如上所示。也就是说，去掉0这个轴，也就是说去掉开始的这个2维的影响。那么我们可以看做是z[]中的2个元素相互重叠，降维。</p>
<p>​    再比如说axis=1，那么就是去掉3的影响，得到结果应该是个(2,4)的张量。也就是对于z[0]和 z[1]分别考虑，取出一个（4）的张量。同时也就是说去掉3行的影响，也就是说按列来对比。</p>
<p>​    对于三维张量来说，如图所示：</p>
<p><img src="https://gitee.com/songx86/SongPicBed/raw/master/img/1570764825003.png" alt="1570782921386"></p>
<p>​    理解为降维即可，就是把那个轴上的数压缩一下到一个平面上。2是axis=0；3是axis=1；4是axis=2。</p>
<p>​    四维及其更高虽然说不能展示出来，但是可以通过相同的方式来理解。也就是看得到的结果是几维的，然后相应的比较。其他sum函数等等同理，只是对于数的操作不同，这里是取max，sum就是把重叠的数加起来啦。</p>
<hr>
<h2 id="单变量-多变量分布实例"><a href="#单变量-多变量分布实例" class="headerlink" title="单变量/多变量分布实例"></a>单变量/多变量分布实例</h2><blockquote>
<ul>
<li>单变量分布(正态分布)的例子：</li>
</ul>
<pre class="line-numbers language-python" data-language="python"><code class="language-python"><span class="token operator">></span>In<span class="token punctuation">[</span><span class="token number">3</span><span class="token punctuation">]</span><span class="token punctuation">:</span>
<span class="token keyword">import</span> zhusuan <span class="token keyword">as</span> zs
<span class="token keyword">import</span> tensorflow <span class="token keyword">as</span> tf
_ <span class="token operator">=</span> tf<span class="token punctuation">.</span>InteractiveSession<span class="token punctuation">(</span><span class="token punctuation">)</span>
b <span class="token operator">=</span> zs<span class="token punctuation">.</span>distributions<span class="token punctuation">.</span>Normal<span class="token punctuation">(</span>
 <span class="token punctuation">[</span>
     <span class="token punctuation">[</span><span class="token punctuation">[</span><span class="token operator">-</span><span class="token number">1</span><span class="token punctuation">.</span><span class="token punctuation">,</span><span class="token number">1</span><span class="token punctuation">.</span><span class="token punctuation">]</span><span class="token punctuation">,</span><span class="token punctuation">[</span><span class="token operator">-</span><span class="token number">1</span><span class="token punctuation">.</span><span class="token punctuation">,</span><span class="token operator">-</span><span class="token number">2</span><span class="token punctuation">.</span><span class="token punctuation">]</span><span class="token punctuation">]</span><span class="token punctuation">,</span>
        <span class="token punctuation">[</span><span class="token punctuation">[</span><span class="token number">9</span><span class="token punctuation">.</span><span class="token punctuation">,</span><span class="token number">1</span><span class="token punctuation">.</span><span class="token punctuation">]</span><span class="token punctuation">,</span><span class="token punctuation">[</span><span class="token number">1</span><span class="token punctuation">.</span><span class="token punctuation">,</span><span class="token number">2</span><span class="token punctuation">.</span><span class="token punctuation">]</span><span class="token punctuation">]</span>
    <span class="token punctuation">]</span><span class="token punctuation">,</span>logstd<span class="token operator">=</span><span class="token punctuation">[</span><span class="token number">0</span><span class="token punctuation">.</span><span class="token punctuation">,</span><span class="token number">1</span><span class="token punctuation">.</span><span class="token punctuation">]</span><span class="token punctuation">)</span>
   
   
In <span class="token punctuation">[</span><span class="token number">4</span><span class="token punctuation">]</span><span class="token punctuation">:</span><span class="token comment"># batch_shape显示有多少批被输入到分布的形状中</span>
<span class="token comment"># 这里是2维有2个，1维有2个，0维有2个</span>
<span class="token comment"># 或者这样说：[2,2,2]三个数表示有3层，第一层里面有2，第二层里面有2，第三层里面有2</span>
b<span class="token punctuation">.</span>batch_shape<span class="token punctuation">.</span><span class="token builtin">eval</span><span class="token punctuation">(</span><span class="token punctuation">)</span>

Out<span class="token punctuation">[</span><span class="token number">4</span><span class="token punctuation">]</span><span class="token punctuation">:</span>array<span class="token punctuation">(</span><span class="token punctuation">[</span><span class="token number">2</span><span class="token punctuation">,</span> <span class="token number">2</span><span class="token punctuation">,</span> <span class="token number">2</span><span class="token punctuation">]</span><span class="token punctuation">)</span>


In <span class="token punctuation">[</span><span class="token number">5</span><span class="token punctuation">]</span><span class="token punctuation">:</span>b<span class="token punctuation">.</span>value_shape<span class="token punctuation">.</span><span class="token builtin">eval</span><span class="token punctuation">(</span><span class="token punctuation">)</span>
 
Out<span class="token punctuation">[</span><span class="token number">5</span><span class="token punctuation">]</span><span class="token punctuation">:</span>array<span class="token punctuation">(</span><span class="token punctuation">[</span><span class="token punctuation">]</span><span class="token punctuation">,</span> dtype<span class="token operator">=</span>int32<span class="token punctuation">)</span>
   

In <span class="token punctuation">[</span><span class="token number">9</span><span class="token punctuation">]</span><span class="token punctuation">:</span>tf<span class="token punctuation">.</span>shape<span class="token punctuation">(</span>b<span class="token punctuation">.</span>sample<span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token punctuation">.</span><span class="token builtin">eval</span><span class="token punctuation">(</span> <span class="token punctuation">)</span>

Out<span class="token punctuation">[</span><span class="token number">9</span><span class="token punctuation">]</span><span class="token punctuation">:</span>array<span class="token punctuation">(</span><span class="token punctuation">[</span><span class="token number">2</span><span class="token punctuation">,</span> <span class="token number">2</span><span class="token punctuation">,</span> <span class="token number">2</span><span class="token punctuation">]</span><span class="token punctuation">)</span>

 
In <span class="token punctuation">[</span><span class="token number">11</span><span class="token punctuation">]</span><span class="token punctuation">:</span>tf<span class="token punctuation">.</span>shape<span class="token punctuation">(</span>b<span class="token punctuation">.</span>sample<span class="token punctuation">(</span><span class="token number">1</span><span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token punctuation">.</span><span class="token builtin">eval</span><span class="token punctuation">(</span><span class="token punctuation">)</span>
   
Out<span class="token punctuation">[</span><span class="token number">11</span><span class="token punctuation">]</span><span class="token punctuation">:</span>array<span class="token punctuation">(</span><span class="token punctuation">[</span><span class="token number">1</span><span class="token punctuation">,</span> <span class="token number">2</span><span class="token punctuation">,</span> <span class="token number">2</span><span class="token punctuation">,</span> <span class="token number">2</span><span class="token punctuation">]</span><span class="token punctuation">)</span>

 
In <span class="token punctuation">[</span><span class="token number">12</span><span class="token punctuation">]</span><span class="token punctuation">:</span>tf<span class="token punctuation">.</span>shape<span class="token punctuation">(</span>b<span class="token punctuation">.</span>sample<span class="token punctuation">(</span><span class="token number">2</span><span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token punctuation">.</span><span class="token builtin">eval</span><span class="token punctuation">(</span><span class="token punctuation">)</span>
   
Out<span class="token punctuation">[</span><span class="token number">12</span><span class="token punctuation">]</span><span class="token punctuation">:</span>array<span class="token punctuation">(</span><span class="token punctuation">[</span><span class="token number">2</span><span class="token punctuation">,</span> <span class="token number">2</span><span class="token punctuation">,</span> <span class="token number">2</span><span class="token punctuation">,</span> <span class="token number">2</span><span class="token punctuation">]</span><span class="token punctuation">)</span>

 
In <span class="token punctuation">[</span><span class="token number">13</span><span class="token punctuation">]</span><span class="token punctuation">:</span>b<span class="token punctuation">.</span>get_batch_shape<span class="token punctuation">(</span><span class="token punctuation">)</span>
   
Out<span class="token punctuation">[</span><span class="token number">13</span><span class="token punctuation">]</span><span class="token punctuation">:</span>TensorShape<span class="token punctuation">(</span><span class="token punctuation">[</span>Dimension<span class="token punctuation">(</span><span class="token number">2</span><span class="token punctuation">)</span><span class="token punctuation">,</span> Dimension<span class="token punctuation">(</span><span class="token number">2</span><span class="token punctuation">)</span><span class="token punctuation">,</span> Dimension<span class="token punctuation">(</span><span class="token number">2</span><span class="token punctuation">)</span><span class="token punctuation">]</span><span class="token punctuation">)</span>

 
In <span class="token punctuation">[</span><span class="token number">14</span><span class="token punctuation">]</span><span class="token punctuation">:</span>b<span class="token punctuation">.</span>get_value_shape<span class="token punctuation">(</span><span class="token punctuation">)</span>
   
Out<span class="token punctuation">[</span><span class="token number">14</span><span class="token punctuation">]</span><span class="token punctuation">:</span>TensorShape<span class="token punctuation">(</span><span class="token punctuation">[</span><span class="token punctuation">]</span><span class="token punctuation">)</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>



<p>多变量分布的例子（使用oneHot分类）：</p>
<pre class="line-numbers language-python" data-language="python"><code class="language-python"><span class="token operator">></span><span class="token keyword">import</span> zhusuan <span class="token keyword">as</span> zs
<span class="token keyword">import</span> tensorflow <span class="token keyword">as</span> tf
_ <span class="token operator">=</span> tf<span class="token punctuation">.</span>InteractiveSession<span class="token punctuation">(</span><span class="token punctuation">)</span>

c <span class="token operator">=</span> zs<span class="token punctuation">.</span>distributions<span class="token punctuation">.</span>OnehotCategorical<span class="token punctuation">(</span><span class="token punctuation">[</span><span class="token punctuation">[</span><span class="token number">0</span><span class="token punctuation">.</span><span class="token punctuation">,</span><span class="token number">1</span><span class="token punctuation">.</span><span class="token punctuation">,</span><span class="token operator">-</span><span class="token number">1</span><span class="token punctuation">.</span><span class="token punctuation">]</span><span class="token punctuation">,</span>
                                     <span class="token punctuation">[</span><span class="token number">2</span><span class="token punctuation">.</span><span class="token punctuation">,</span><span class="token number">3</span><span class="token punctuation">.</span><span class="token punctuation">,</span><span class="token number">4</span><span class="token punctuation">.</span><span class="token punctuation">]</span><span class="token punctuation">]</span><span class="token punctuation">)</span>
<span class="token comment"># batch，批次，2个批次，也就是说是2维数组</span>
   c<span class="token punctuation">.</span>batch_shape<span class="token punctuation">.</span><span class="token builtin">eval</span><span class="token punctuation">(</span><span class="token punctuation">)</span>
array<span class="token punctuation">(</span><span class="token punctuation">[</span><span class="token number">2</span><span class="token punctuation">]</span><span class="token punctuation">)</span>

<span class="token comment"># 每个批次有3个数</span>
c<span class="token punctuation">.</span>value_shape<span class="token punctuation">.</span><span class="token builtin">eval</span><span class="token punctuation">(</span><span class="token punctuation">)</span>
array<span class="token punctuation">(</span><span class="token punctuation">[</span><span class="token number">3</span><span class="token punctuation">]</span><span class="token punctuation">)</span>

tf<span class="token punctuation">.</span>shape<span class="token punctuation">(</span>c<span class="token punctuation">.</span>sample<span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token punctuation">.</span><span class="token builtin">eval</span><span class="token punctuation">(</span><span class="token punctuation">)</span>
array<span class="token punctuation">(</span><span class="token punctuation">[</span><span class="token number">2</span><span class="token punctuation">,</span> <span class="token number">3</span><span class="token punctuation">]</span><span class="token punctuation">)</span>

tf<span class="token punctuation">.</span>shape<span class="token punctuation">(</span>c<span class="token punctuation">.</span>sample<span class="token punctuation">(</span><span class="token number">1</span><span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token punctuation">.</span><span class="token builtin">eval</span><span class="token punctuation">(</span><span class="token punctuation">)</span>
array<span class="token punctuation">(</span><span class="token punctuation">[</span><span class="token number">1</span><span class="token punctuation">,</span> <span class="token number">2</span><span class="token punctuation">,</span> <span class="token number">3</span><span class="token punctuation">]</span><span class="token punctuation">)</span>

tf<span class="token punctuation">.</span>shape<span class="token punctuation">(</span>c<span class="token punctuation">.</span>sample<span class="token punctuation">(</span><span class="token number">10</span><span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token punctuation">.</span><span class="token builtin">eval</span><span class="token punctuation">(</span><span class="token punctuation">)</span>
array<span class="token punctuation">(</span><span class="token punctuation">[</span><span class="token number">10</span><span class="token punctuation">,</span>  <span class="token number">2</span><span class="token punctuation">,</span>  <span class="token number">3</span><span class="token punctuation">]</span><span class="token punctuation">)</span>

<span class="token comment"># 输出一下这两个shape看看</span>
<span class="token keyword">print</span><span class="token punctuation">(</span><span class="token string">'c.batch_shape == '</span><span class="token punctuation">,</span>c<span class="token punctuation">.</span>batch_shape<span class="token punctuation">)</span>
<span class="token keyword">print</span><span class="token punctuation">(</span><span class="token string">'c.batch_shape.eval() == '</span><span class="token punctuation">,</span>c<span class="token punctuation">.</span>batch_shape<span class="token punctuation">.</span><span class="token builtin">eval</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">)</span>
<span class="token keyword">print</span><span class="token punctuation">(</span><span class="token string">'c.value_shape == '</span><span class="token punctuation">,</span>c<span class="token punctuation">.</span>value_shape<span class="token punctuation">)</span>
<span class="token keyword">print</span><span class="token punctuation">(</span><span class="token string">'c.value_shape.eval() == '</span><span class="token punctuation">,</span>c<span class="token punctuation">.</span>value_shape<span class="token punctuation">.</span><span class="token builtin">eval</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">)</span>

c<span class="token punctuation">.</span>batch_shape <span class="token operator">==</span>  Tensor<span class="token punctuation">(</span><span class="token string">"shape_as_tensor_13:0"</span><span class="token punctuation">,</span> shape<span class="token operator">=</span><span class="token punctuation">(</span><span class="token number">1</span><span class="token punctuation">,</span><span class="token punctuation">)</span><span class="token punctuation">,</span> dtype<span class="token operator">=</span>int32<span class="token punctuation">)</span>
c<span class="token punctuation">.</span>batch_shape<span class="token punctuation">.</span><span class="token builtin">eval</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token operator">==</span>  <span class="token punctuation">[</span><span class="token number">2</span><span class="token punctuation">]</span>
c<span class="token punctuation">.</span>value_shape <span class="token operator">==</span>  Tensor<span class="token punctuation">(</span><span class="token string">"shape_as_tensor_15:0"</span><span class="token punctuation">,</span> shape<span class="token operator">=</span><span class="token punctuation">(</span><span class="token number">1</span><span class="token punctuation">,</span><span class="token punctuation">)</span><span class="token punctuation">,</span> dtype<span class="token operator">=</span>int32<span class="token punctuation">)</span>
c<span class="token punctuation">.</span>value_shape<span class="token punctuation">.</span><span class="token builtin">eval</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token operator">==</span>  <span class="token punctuation">[</span><span class="token number">3</span><span class="token punctuation">]</span>

<span class="token comment"># 输出一下sample</span>
<span class="token keyword">print</span><span class="token punctuation">(</span><span class="token string">'c.sample() == '</span><span class="token punctuation">,</span>c<span class="token punctuation">.</span>sample<span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">.</span><span class="token builtin">eval</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">)</span>
<span class="token keyword">print</span><span class="token punctuation">(</span><span class="token string">'c.sample(1) == '</span><span class="token punctuation">,</span>c<span class="token punctuation">.</span>sample<span class="token punctuation">(</span><span class="token number">1</span><span class="token punctuation">)</span><span class="token punctuation">.</span><span class="token builtin">eval</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">)</span>
<span class="token keyword">print</span><span class="token punctuation">(</span><span class="token string">'c.sample(10) == '</span><span class="token punctuation">,</span>c<span class="token punctuation">.</span>sample<span class="token punctuation">(</span><span class="token number">10</span><span class="token punctuation">)</span><span class="token punctuation">.</span><span class="token builtin">eval</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">)</span>

c<span class="token punctuation">.</span>sample<span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token operator">==</span>  <span class="token punctuation">[</span><span class="token punctuation">[</span><span class="token number">0</span> <span class="token number">1</span> <span class="token number">0</span><span class="token punctuation">]</span>
<span class="token punctuation">[</span><span class="token number">0</span> <span class="token number">0</span> <span class="token number">1</span><span class="token punctuation">]</span><span class="token punctuation">]</span>
c<span class="token punctuation">.</span>sample<span class="token punctuation">(</span><span class="token number">1</span><span class="token punctuation">)</span> <span class="token operator">==</span>  <span class="token punctuation">[</span><span class="token punctuation">[</span><span class="token punctuation">[</span><span class="token number">0</span> <span class="token number">1</span> <span class="token number">0</span><span class="token punctuation">]</span>
 <span class="token punctuation">[</span><span class="token number">1</span> <span class="token number">0</span> <span class="token number">0</span><span class="token punctuation">]</span><span class="token punctuation">]</span><span class="token punctuation">]</span>
c<span class="token punctuation">.</span>sample<span class="token punctuation">(</span><span class="token number">10</span><span class="token punctuation">)</span> <span class="token operator">==</span>  <span class="token punctuation">[</span><span class="token punctuation">[</span><span class="token punctuation">[</span><span class="token number">0</span> <span class="token number">1</span> <span class="token number">0</span><span class="token punctuation">]</span>
  <span class="token punctuation">[</span><span class="token number">0</span> <span class="token number">0</span> <span class="token number">1</span><span class="token punctuation">]</span><span class="token punctuation">]</span>

  <span class="token punctuation">[</span><span class="token punctuation">[</span><span class="token number">0</span> <span class="token number">1</span> <span class="token number">0</span><span class="token punctuation">]</span>
<span class="token punctuation">[</span><span class="token number">0</span> <span class="token number">0</span> <span class="token number">1</span><span class="token punctuation">]</span><span class="token punctuation">]</span>
 
  <span class="token punctuation">[</span><span class="token punctuation">[</span><span class="token number">0</span> <span class="token number">0</span> <span class="token number">1</span><span class="token punctuation">]</span>
<span class="token punctuation">[</span><span class="token number">0</span> <span class="token number">0</span> <span class="token number">1</span><span class="token punctuation">]</span><span class="token punctuation">]</span>
 
  <span class="token punctuation">[</span><span class="token punctuation">[</span><span class="token number">0</span> <span class="token number">1</span> <span class="token number">0</span><span class="token punctuation">]</span>
<span class="token punctuation">[</span><span class="token number">0</span> <span class="token number">0</span> <span class="token number">1</span><span class="token punctuation">]</span><span class="token punctuation">]</span>
 
  <span class="token punctuation">[</span><span class="token punctuation">[</span><span class="token number">0</span> <span class="token number">1</span> <span class="token number">0</span><span class="token punctuation">]</span>
<span class="token punctuation">[</span><span class="token number">0</span> <span class="token number">1</span> <span class="token number">0</span><span class="token punctuation">]</span><span class="token punctuation">]</span>
 
  <span class="token punctuation">[</span><span class="token punctuation">[</span><span class="token number">0</span> <span class="token number">1</span> <span class="token number">0</span><span class="token punctuation">]</span>
<span class="token punctuation">[</span><span class="token number">0</span> <span class="token number">1</span> <span class="token number">0</span><span class="token punctuation">]</span><span class="token punctuation">]</span>
 
  <span class="token punctuation">[</span><span class="token punctuation">[</span><span class="token number">0</span> <span class="token number">1</span> <span class="token number">0</span><span class="token punctuation">]</span>
<span class="token punctuation">[</span><span class="token number">0</span> <span class="token number">0</span> <span class="token number">1</span><span class="token punctuation">]</span><span class="token punctuation">]</span>
 
  <span class="token punctuation">[</span><span class="token punctuation">[</span><span class="token number">0</span> <span class="token number">1</span> <span class="token number">0</span><span class="token punctuation">]</span>
<span class="token punctuation">[</span><span class="token number">0</span> <span class="token number">0</span> <span class="token number">1</span><span class="token punctuation">]</span><span class="token punctuation">]</span>
 
  <span class="token punctuation">[</span><span class="token punctuation">[</span><span class="token number">1</span> <span class="token number">0</span> <span class="token number">0</span><span class="token punctuation">]</span>
<span class="token punctuation">[</span><span class="token number">0</span> <span class="token number">0</span> <span class="token number">1</span><span class="token punctuation">]</span><span class="token punctuation">]</span>
 
  <span class="token punctuation">[</span><span class="token punctuation">[</span><span class="token number">0</span> <span class="token number">1</span> <span class="token number">0</span><span class="token punctuation">]</span>
<span class="token punctuation">[</span><span class="token number">0</span> <span class="token number">0</span> <span class="token number">1</span><span class="token punctuation">]</span><span class="token punctuation">]</span><span class="token punctuation">]</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>



<p>在某些情况下，一批随机变量可以分组到一个独立事件中，以便于可以一起计算他们的概率。这是通过设置group_ndims参数（默认是0）来实现的。batch_shape中最后的group_ndims个批次被分组为一个事件。 例如，Normal(…，group_ndims = 1）会将其batch_shape的最后一个axis设置为独立事件，即具有一致协方差矩阵（<em>在统计学与概率论中，协方差矩阵的每个元素是<strong>各个向量元素之间的协方差</strong>，是从标量随机变量到高维度随机向量的自然推广</em>）的多元正态分布。</p>
</blockquote>
<hr>
<h3 id="补充：-tf-InteractiveSession"><a href="#补充：-tf-InteractiveSession" class="headerlink" title="补充：_ = tf.InteractiveSession()"></a>补充：_ = tf.InteractiveSession()</h3><p>TensorFlow的前后端的连接依靠于session，使用TensorFlow程序的流程构建计算图完成之后，在session中启动运行。</p>
<h4 id="补充：Sesssion"><a href="#补充：Sesssion" class="headerlink" title="补充：Sesssion"></a>补充：Sesssion</h4><p>我们在Python中需要做一些计算操作时一般会使用NumPy，NumPy在做矩阵操作等复杂的计算的时候会使用其他语言(C/C++)来实现这些计算逻辑，来保证计算的高效性。但是频繁的在多个编程语言间切换也会有一定的耗时，如果只是单机操作这些耗时可能会忽略不计，但是如果在分布式并行计算中，计算操作可能分布在不同的CPU、GPU甚至不同的机器中，这些耗时可能会比较严重。<br>TensorFlow 底层是使用C++实现，这样可以保证计算效率，并使用 tf.Session类来连接客户端程序与C++运行时。上层的Python、Java等代码用来设计、定义模型，构建的Graph，最后通过tf.Session.run()方法传递给底层执行。</p>
<p>对于像Python原生编辑器，或者jupyter这样的基于浏览器的python编辑器，要一段一段的输入代码，  于是就有了 tf.InteractiveSession() 这样的交互式会话，它不需要用 “sess.run(变量)”这种形式，而是定义好会话对象后，每次执行tensor时，调用tensor.eval()即可。</p>
<h4 id="补充：eval"><a href="#补充：eval" class="headerlink" title="补充：eval()"></a>补充：eval()</h4><p>eval() 其实就是tf.Tensor的Session.run() 的另外一种写法，但两者有差别:</p>
<ol>
<li>eval(): 将<strong>字符串string对象转化为有效的表达式</strong>参与求值运算返回计算结果</li>
<li>eval()也是<strong>启动计算的一种方式</strong>。基于Tensorflow的基本原理，首先需要定义图，然后计算图，其中计算图的函数常见的有run()函数，如sess.run()。同样eval()也是此类函数，</li>
<li>要注意的是，eval()只能用于tf.Tensor类对象，也就是有输出的Operation。对于没有输出的Operation, 可以用.run()或者Session.run()；Session.run()没有这个限制。</li>
</ol>
<h1 id="贝叶斯网络"><a href="#贝叶斯网络" class="headerlink" title="贝叶斯网络"></a>贝叶斯网络</h1><blockquote>
<p>在ZhuSuan中，我们支持将概率模型构建为贝叶斯网络，即定向图形模型。 下面我们使用一个简单的贝叶斯线性回归示例来说明这一点。 模型的生成过程是<br>$$<br>w \mbox{<del>}  N(0,\alpha^2I)\<br>y \mbox{</del>} N(w^Tx,\beta^2)<br>$$<br>其中<strong>x表示线性回归中的输入特征</strong>。 我们应用贝叶斯处理并假设<strong>回归权重w</strong>的正态先验分布。 假设输入要素有5个维度。 为简单起见，我们将输入定义为占位符并设置超参数：</p>
<pre class="line-numbers language-python" data-language="python"><code class="language-python">x <span class="token operator">=</span> tf<span class="token punctuation">.</span>placeholder<span class="token punctuation">(</span>tf<span class="token punctuation">.</span>float32<span class="token punctuation">,</span> shape<span class="token operator">=</span><span class="token punctuation">[</span><span class="token number">5</span><span class="token punctuation">]</span><span class="token punctuation">)</span>
alpha <span class="token operator">=</span> <span class="token number">1</span><span class="token punctuation">.</span>
beta <span class="token operator">=</span> <span class="token number">0.1</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span></span></code></pre>
</blockquote>
<hr>
<h4 id="补充：超参数-hyper-parameters"><a href="#补充：超参数-hyper-parameters" class="headerlink" title="补充：超参数 hyper-parameters"></a>补充：超参数 hyper-parameters</h4><ol>
<li>参数(parameters)/模型参数</li>
</ol>
<p>　<strong>由模型通过学习得到的变量</strong>，比如权重w和偏置b</p>
<ol start="2">
<li><p>超参数(hyperparameters)/算法参数</p>
<p><strong>根据经验进行手动设定</strong>，影响到权重w和偏置b的大小，比如迭代次数、隐藏层的层数、每层神经元的个数、学习速率等</p>
</li>
</ol>
<h4 id="补充：tf-placeholder"><a href="#补充：tf-placeholder" class="headerlink" title="补充：tf.placeholder()"></a>补充：tf.placeholder()</h4><p>定义‘符号’变量，也称为占位符。相当于定义一个变量，但是不赋值，到了使用的时候再进行赋值。</p>
<p>​    Tensorflow的设计理念称之为计算流图，在编写程序时，首先构筑整个系统的graph，代码并不会直接生效，这一点和python的其他数值计算库（如Numpy等）不同，graph为静态的，类似于docker中的镜像。然后，在实际的运行时，启动一个session，程序才会真正的运行。这样做的好处就是：避免反复地切换底层程序实际运行的上下文，tensorflow帮你优化整个系统的代码。我们知道，很多python程序的底层为C语言或者其他语言，执行一行脚本，就要切换一次，是有成本的，tensorflow通过计算流图的方式，帮你优化整个session需要执行的代码，还是很有优势的。</p>
<p>​    所以placeholder()函数是在神经网络构建graph的时候在模型中的占位，此时并没有把要输入的数据传入模型，它只会分配必要的内存。等建立session，在会话中，运行模型的时候通过feed_dict()函数向占位符喂入数据。</p>
<hr>
<h2 id="BayesianNet实例"><a href="#BayesianNet实例" class="headerlink" title="BayesianNet实例"></a>BayesianNet实例</h2><blockquote>
<p>要定义模型，第一步是构造一个BayesianNet实例：</p>
<pre class="line-numbers language-python" data-language="python"><code class="language-python">bn <span class="token operator">=</span> zs<span class="token punctuation">.</span>BayesianNet<span class="token punctuation">(</span><span class="token punctuation">)</span><span aria-hidden="true" class="line-numbers-rows"><span></span></span></code></pre>
<p>贝叶斯网络将一组随机变量的联合分布的依存关系描述为有向图。 为此，BayesianNet实例可以保留两种节点：</p>
<ul>
<li>随机节点。 它们是图形模型中的随机变量。  w节点可以构造为：</li>
</ul>
<pre class="line-numbers language-python" data-language="python"><code class="language-python">w <span class="token operator">=</span> bn<span class="token punctuation">.</span>normal<span class="token punctuation">(</span><span class="token string">"w"</span><span class="token punctuation">,</span> tf<span class="token punctuation">.</span>zeros<span class="token punctuation">(</span><span class="token punctuation">[</span>x<span class="token punctuation">.</span>shape<span class="token punctuation">[</span><span class="token operator">-</span><span class="token number">1</span><span class="token punctuation">]</span><span class="token punctuation">]</span><span class="token punctuation">)</span><span class="token punctuation">,</span> std<span class="token operator">=</span>alpha<span class="token punctuation">)</span><span aria-hidden="true" class="line-numbers-rows"><span></span></span></code></pre>

<p>这里w是一个服从正态分布的StochasticTensor随机张量（StochasticTensor类，类似于Tensor，可以被传到任何Tensor操作中）:</p>
<pre class="line-numbers language-python" data-language="python"><code class="language-python"><span class="token operator">>></span><span class="token operator">></span> <span class="token keyword">print</span><span class="token punctuation">(</span>w<span class="token punctuation">)</span>
<span class="token operator">&lt;</span>zhusuan<span class="token punctuation">.</span>framework<span class="token punctuation">.</span>bn<span class="token punctuation">.</span>StochasticTensor <span class="token builtin">object</span> at <span class="token punctuation">.</span><span class="token punctuation">.</span><span class="token punctuation">.</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span></span></code></pre>

<p>对于<code>zhusuan.distributions</code>中任何可用的分布，我们都能在<code>BayesianNet</code>中找到一个方法来创建相应的随机节点。<code>StochasticTenor</code>实例类类似于Tensor，这意味着你可以将StochasticTenor类与任何TensorFlow原语混用。例如，线性回归的预测均值是w与输入x之间的内积：</p>
<pre class="line-numbers language-python" data-language="python"><code class="language-python">y_mean <span class="token operator">=</span> tf<span class="token punctuation">.</span>reduce_sum<span class="token punctuation">(</span>w <span class="token operator">*</span> x<span class="token punctuation">,</span> axis<span class="token operator">=</span><span class="token operator">-</span><span class="token number">1</span><span class="token punctuation">)</span><span aria-hidden="true" class="line-numbers-rows"><span></span></span></code></pre>
</blockquote>
<p><a target="_blank" rel="noopener" href="https://zhusuan.readthedocs.io/en/latest/api/zhusuan.framework.html#zhusuan.framework.bn.StochasticTensor">StochasticTenor类说明</a></p>
<p>插一句，这里的axis=-1就是说倒数第一个。比如（3,4,5）,axis=-1就是指5，也就是等价于axis=2。</p>
<p>w节点的构造，=bn.nomal(“节点名”，tf构造的全为0的一个数组【维度为x.shape】，标准差为上面定义的alpha)</p>
<p>这里还是关于-1的写法，x.shape[-1]就相当于x.shape[5].</p>
<pre class="line-numbers language-python" data-language="python"><code class="language-python"><span class="token keyword">print</span><span class="token punctuation">(</span>w<span class="token punctuation">.</span>shape<span class="token punctuation">,</span>x<span class="token punctuation">.</span>shape<span class="token punctuation">)</span>
<span class="token punctuation">(</span><span class="token number">5</span><span class="token punctuation">,</span><span class="token punctuation">)</span> <span class="token punctuation">(</span><span class="token number">5</span><span class="token punctuation">,</span><span class="token punctuation">)</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span></span></code></pre>



<h4 id="补充：tf-reduce-sum"><a href="#补充：tf-reduce-sum" class="headerlink" title="补充：tf.reduce_sum()"></a>补充：tf.reduce_sum()</h4><p>reduce_sum应该理解为按相应的轴压缩求和，用于降维。通过设置axis参数按相应轴压缩求和。</p>
<p>关于上面那个内积的计算举例：</p>
<pre class="line-numbers language-python" data-language="python"><code class="language-python">a<span class="token operator">=</span>tf<span class="token punctuation">.</span>constant<span class="token punctuation">(</span><span class="token punctuation">[</span><span class="token number">1</span><span class="token punctuation">,</span><span class="token number">2</span><span class="token punctuation">,</span><span class="token number">3</span><span class="token punctuation">,</span><span class="token number">4</span><span class="token punctuation">,</span><span class="token number">5</span><span class="token punctuation">]</span><span class="token punctuation">)</span>
b<span class="token operator">=</span>tf<span class="token punctuation">.</span>constant<span class="token punctuation">(</span><span class="token punctuation">[</span><span class="token number">2</span><span class="token punctuation">,</span><span class="token number">2</span><span class="token punctuation">,</span><span class="token number">2</span><span class="token punctuation">,</span><span class="token number">2</span><span class="token punctuation">,</span><span class="token number">2</span><span class="token punctuation">]</span><span class="token punctuation">)</span>
c <span class="token operator">=</span> a<span class="token operator">*</span>b
c<span class="token punctuation">.</span><span class="token builtin">eval</span><span class="token punctuation">(</span><span class="token punctuation">)</span>

Out<span class="token punctuation">:</span>array<span class="token punctuation">(</span><span class="token punctuation">[</span> <span class="token number">2</span><span class="token punctuation">,</span>  <span class="token number">4</span><span class="token punctuation">,</span>  <span class="token number">6</span><span class="token punctuation">,</span>  <span class="token number">8</span><span class="token punctuation">,</span> <span class="token number">10</span><span class="token punctuation">]</span><span class="token punctuation">)</span>

tf<span class="token punctuation">.</span>reduce_sum<span class="token punctuation">(</span>a<span class="token operator">*</span>b<span class="token punctuation">,</span>axis<span class="token operator">=</span><span class="token operator">-</span><span class="token number">1</span><span class="token punctuation">)</span><span class="token punctuation">.</span><span class="token builtin">eval</span><span class="token punctuation">(</span><span class="token punctuation">)</span>

Out<span class="token punctuation">:</span><span class="token number">30</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>

<hr>
<h3 id="确定性节点"><a href="#确定性节点" class="headerlink" title="确定性节点"></a>确定性节点</h3><blockquote>
<ul>
<li>确定性节点。</li>
</ul>
<p>确定性节点。 如上面的代码所示，可以使用Tensorflow操作直接构造确定性节点，而BayesianNet不会跟踪它们。 但是，在某些情况下，可以通过deterministic（）方法启用跟踪：</p>
<pre class="line-numbers language-python" data-language="python"><code class="language-python">y_mean <span class="token operator">=</span> bn<span class="token punctuation">.</span>deterministic<span class="token punctuation">(</span><span class="token string">"y_mean"</span><span class="token punctuation">,</span> tf<span class="token punctuation">.</span>reduce_sum<span class="token punctuation">(</span>w <span class="token operator">*</span> x<span class="token punctuation">,</span> axis<span class="token operator">=</span><span class="token operator">-</span><span class="token number">1</span><span class="token punctuation">)</span><span class="token punctuation">)</span><span aria-hidden="true" class="line-numbers-rows"><span></span></span></code></pre>

<p>这使你可以随时从bn获取y_mean张量。</p>
</blockquote>
<p>也就是说，如果在构建过程中这样写的话：</p>
<pre class="line-numbers language-python" data-language="python"><code class="language-python">y_mean <span class="token operator">=</span> tf<span class="token punctuation">.</span>reduce_sum<span class="token punctuation">(</span>w <span class="token operator">*</span> x<span class="token punctuation">,</span> axis<span class="token operator">=</span><span class="token operator">-</span><span class="token number">1</span><span class="token punctuation">)</span><span aria-hidden="true" class="line-numbers-rows"><span></span></span></code></pre>

<p>​    那么bn中将不会有y_mean这个节点的信息。</p>
<pre class="line-numbers language-python" data-language="python"><code class="language-python"><span class="token comment"># 康康这个模型里面有啥节点</span>
<span class="token keyword">print</span><span class="token punctuation">(</span>model_b<span class="token punctuation">.</span>nodes<span class="token punctuation">.</span>keys<span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">)</span>

Out<span class="token punctuation">:</span> dict_keys<span class="token punctuation">(</span><span class="token punctuation">[</span><span class="token string">'w'</span><span class="token punctuation">,</span> <span class="token string">'y_mean'</span><span class="token punctuation">,</span> <span class="token string">'y'</span><span class="token punctuation">]</span><span class="token punctuation">)</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span></span></code></pre>

<p>​    换成deterministic()方法的话，那么就可以从bn中get到y_mean了。</p>
<pre class="line-numbers language-python" data-language="python"><code class="language-python"><span class="token comment"># 康康这个模型里面有啥节点</span>
<span class="token keyword">print</span><span class="token punctuation">(</span>model_b<span class="token punctuation">.</span>nodes<span class="token punctuation">.</span>keys<span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">)</span>

Out<span class="token punctuation">:</span> dict_keys<span class="token punctuation">(</span><span class="token punctuation">[</span><span class="token string">'w'</span><span class="token punctuation">,</span> <span class="token string">'y_mean'</span><span class="token punctuation">,</span> <span class="token string">'y'</span><span class="token punctuation">]</span><span class="token punctuation">)</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span></span></code></pre>

<h3 id="构建贝叶斯网络的完整代码"><a href="#构建贝叶斯网络的完整代码" class="headerlink" title="构建贝叶斯网络的完整代码"></a>构建贝叶斯网络的完整代码</h3><blockquote>
<p>构建贝叶斯线性回归模型的完整代码如下：</p>
<pre class="line-numbers language-python" data-language="python"><code class="language-python"><span class="token keyword">def</span> <span class="token function">bayesian_linear_regression</span><span class="token punctuation">(</span>x<span class="token punctuation">,</span> alpha<span class="token punctuation">,</span> beta<span class="token punctuation">)</span><span class="token punctuation">:</span>
 	bn <span class="token operator">=</span> zs<span class="token punctuation">.</span>BayesianNet<span class="token punctuation">(</span><span class="token punctuation">)</span>
 	w <span class="token operator">=</span> bn<span class="token punctuation">.</span>normal<span class="token punctuation">(</span><span class="token string">"w"</span><span class="token punctuation">,</span> mean<span class="token operator">=</span><span class="token number">0</span><span class="token punctuation">.</span><span class="token punctuation">,</span> std<span class="token operator">=</span>alpha<span class="token punctuation">)</span>
 	y_mean <span class="token operator">=</span> tf<span class="token punctuation">.</span>reduce_sum<span class="token punctuation">(</span>w <span class="token operator">*</span> x<span class="token punctuation">,</span> axis<span class="token operator">=</span><span class="token operator">-</span><span class="token number">1</span><span class="token punctuation">)</span>
 	bn<span class="token punctuation">.</span>normal<span class="token punctuation">(</span><span class="token string">"y"</span><span class="token punctuation">,</span> y_mean<span class="token punctuation">,</span> std<span class="token operator">=</span>beta<span class="token punctuation">)</span>
 	<span class="token keyword">return</span> bn<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>
</blockquote>
<p>步骤总结：</p>
<ol>
<li><p>声明贝叶斯网络实例；</p>
</li>
<li><p>构建一个随机节点w，使用正态分布，均值为0，标准差为alpha。w节点如下公式。</p>
</li>
</ol>
<p>$$<br>w \mbox{~}  N(0,\alpha^2I)<br>$$</p>
<ol start="3">
<li><p>求w*x的和，也就是内积</p>
</li>
<li><p>构建一个名为y的随机节点，使用正态分布，均值为w与x的内积，标准差为beta。x是占位符，传递过来的一个参数，应该是后来要输入的数据。y节点如下公式。<br>$$<br>y \mbox{~} N(w^Tx,\beta^2)<br>$$</p>
</li>
</ol>
<blockquote>
<p> 图形模型的一个独特的特点是<strong>允许随机节点具有不确定的行为</strong>（即是潜在的），我们可以<strong>随时观察它们（然后将它们固定在观察值上）</strong>。 在ZhuSuan中，可以使用观察到的字典参数来初始化BayesianNet，以将观察值分配给某些随机节点，例如： </p>
 <pre class="line-numbers language-python" data-language="python"><code class="language-python">bn <span class="token operator">=</span> zs<span class="token punctuation">.</span>BayesianNet<span class="token punctuation">(</span>observed<span class="token operator">=</span><span class="token punctuation">&#123;</span><span class="token string">"w"</span><span class="token punctuation">:</span> w_obs<span class="token punctuation">&#125;</span><span class="token punctuation">)</span><span aria-hidden="true" class="line-numbers-rows"><span></span></span></code></pre>

<p> 会使得随机变量w 作为w_obs被观察。这样做的的结果是在bn中，y_mean是根据w的观测值（w_obs）计算的。  对于未被观察的随机节点，当相应的StochasticTensor参与使用Tensor的计算或feed到Tensorflow操作中时，将使用其sample。  在此示例中，这意味着如果我们不对bn进行任何观察，则w的sample将会被用于计算y_mean。 </p>
<p> 尽管上述方法允许将观察值分配给随机节点，但在大多数情况下，<strong>首先定义图形模型然后在需要时传递观察值更为方便</strong>。  此外，该模型应<strong>允许查询具有不同观察值配置</strong>。 为了启用此工作流程，我们引入了一个新的类MetaBayesianNet。  从概念上讲，我们可以将MetaBayesianNet实例视为原始模型，并将BayesianNet视为确定的观察结果。  正如我们将看到的那样，BayesianNet实例可以从其元类实例惰性构造。</p>
<p> 我们要将模型定义为MetaBayesianNet是非常容易办到的。 上面的代码没有任何变化，只是向该函数添加了一个函数装饰器：</p>
 <pre class="line-numbers language-python" data-language="python"><code class="language-python"><span class="token decorator annotation punctuation">@zs<span class="token punctuation">.</span>meta_bayesian_net</span><span class="token punctuation">(</span>scope<span class="token operator">=</span><span class="token string">"model"</span><span class="token punctuation">)</span>
<span class="token keyword">def</span> <span class="token function">bayesian_linear_regression</span><span class="token punctuation">(</span>x<span class="token punctuation">,</span> alpha<span class="token punctuation">,</span> beta<span class="token punctuation">)</span><span class="token punctuation">:</span>
 bn <span class="token operator">=</span> zs<span class="token punctuation">.</span>BayesianNet<span class="token punctuation">(</span><span class="token punctuation">)</span>
 w <span class="token operator">=</span> bn<span class="token punctuation">.</span>normal<span class="token punctuation">(</span><span class="token string">"w"</span><span class="token punctuation">,</span> mean<span class="token operator">=</span><span class="token number">0</span><span class="token punctuation">.</span><span class="token punctuation">,</span> std<span class="token operator">=</span>alpha<span class="token punctuation">)</span>
 y_mean <span class="token operator">=</span> tf<span class="token punctuation">.</span>reduce_sum<span class="token punctuation">(</span>w <span class="token operator">*</span> x<span class="token punctuation">,</span> axis<span class="token operator">=</span><span class="token operator">-</span><span class="token number">1</span><span class="token punctuation">)</span>
 bn<span class="token punctuation">.</span>normal<span class="token punctuation">(</span><span class="token string">"y"</span><span class="token punctuation">,</span> y_mean<span class="token punctuation">,</span> std<span class="token operator">=</span>beta<span class="token punctuation">)</span>
 <span class="token keyword">return</span> bn<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>

<p> 由<code>zs.meta_bayesian_net()</code>注释的函数将返回<code>MetaBayesianNet</code>而不是原始的<code>BayesianNet</code>实例： </p>
 <pre class="line-numbers language-python" data-language="python"><code class="language-python"><span class="token operator">>></span><span class="token operator">></span> model <span class="token operator">=</span> bayesian_linear_regression<span class="token punctuation">(</span>x<span class="token punctuation">,</span> alpha<span class="token punctuation">,</span> beta<span class="token punctuation">)</span>

<span class="token operator">>></span><span class="token operator">></span> <span class="token keyword">print</span><span class="token punctuation">(</span>model<span class="token punctuation">)</span>
<span class="token operator">&lt;</span>zhusuan<span class="token punctuation">.</span>framework<span class="token punctuation">.</span>meta_bn<span class="token punctuation">.</span>MetaBayesianNet <span class="token builtin">object</span> at <span class="token punctuation">.</span><span class="token punctuation">.</span><span class="token punctuation">.</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span></span></code></pre>

<p> 正如我们已经提到的，<strong>MetaBayesianNet可以允许不同的观察配置</strong>。 这是通过其<code>observe()</code>方法实现的。 我们可以将观察值作为命名参数传递，它将返回相应的BayesianNet实例，例如：</p>
 <pre class="line-numbers language-python" data-language="python"><code class="language-python">bn <span class="token operator">=</span> model<span class="token punctuation">.</span>observe<span class="token punctuation">(</span>w<span class="token operator">=</span>w_obs<span class="token punctuation">)</span><span aria-hidden="true" class="line-numbers-rows"><span></span></span></code></pre>

<p> 会将w在<code>BayesianNet</code>类返回的实例bn中设置为被观察的。 使用不同的命名参数调用上述函数（observe)，可以用不同的观察结果observation实例化BayesianNet，<u><strong>这类似于概率图模型的常见行为。</strong></u> </p>
<blockquote>
<p>传递的观测值observation必须与StochasticTensor具有相同的类型和形状。</p>
</blockquote>
<p> 如果<strong>你在模型构造函数中创建了TensorFlow变量，你可能想将其重用于具有不同观察值的贝叶斯网络实例</strong>。  ZhuSuan中还有另一个函数装饰器，称为reuse_variables（），以方便使用。你可以将其添加到任何创建Tensorflow变量的函数中：</p>
 <pre class="line-numbers language-python" data-language="python"><code class="language-python"><span class="token comment"># 构建BayesianNet重用变量</span>
<span class="token decorator annotation punctuation">@zs<span class="token punctuation">.</span>reuse_variables</span><span class="token punctuation">(</span>scope<span class="token operator">=</span><span class="token string">"model"</span><span class="token punctuation">)</span>
<span class="token keyword">def</span> <span class="token function">build_model</span><span class="token punctuation">(</span><span class="token punctuation">.</span><span class="token punctuation">.</span><span class="token punctuation">.</span><span class="token punctuation">)</span><span class="token punctuation">:</span>
 bn <span class="token operator">=</span> zs<span class="token punctuation">.</span>BayesianNet<span class="token punctuation">(</span><span class="token punctuation">)</span>
 <span class="token punctuation">.</span><span class="token punctuation">.</span><span class="token punctuation">.</span>
 <span class="token keyword">return</span> bn<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>

<p> 或等效地，在@zs.meta_bayesian_net（）装饰器中打开redirect_variables选项：</p>
 <pre class="line-numbers language-python" data-language="python"><code class="language-python"><span class="token comment"># 构建MetaBayesianNet重用变量</span>
<span class="token decorator annotation punctuation">@zs<span class="token punctuation">.</span>meta_bayesian_net</span><span class="token punctuation">(</span>scope<span class="token operator">=</span><span class="token string">"model"</span><span class="token punctuation">,</span> reuse_variables<span class="token operator">=</span><span class="token boolean">True</span><span class="token punctuation">)</span>
<span class="token keyword">def</span> <span class="token function">build_model</span><span class="token punctuation">(</span><span class="token punctuation">.</span><span class="token punctuation">.</span><span class="token punctuation">.</span><span class="token punctuation">)</span><span class="token punctuation">:</span>
 bn <span class="token operator">=</span> zs<span class="token punctuation">.</span>BayesianNet<span class="token punctuation">(</span><span class="token punctuation">)</span>
 <span class="token punctuation">.</span><span class="token punctuation">.</span><span class="token punctuation">.</span>
 <span class="token keyword">return</span> bn<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>
</blockquote>
<h4 id="总结：MetaBayesianNet与BayesianNet"><a href="#总结：MetaBayesianNet与BayesianNet" class="headerlink" title="总结：MetaBayesianNet与BayesianNet"></a>总结：MetaBayesianNet与BayesianNet</h4><p>MetaBayesianNet类是可变的BayesianNet，可以通过传递不同的观察值来构建贝叶斯网络。</p>
<p>在一个构造BayesianNet的函数上加个装饰器就将返回值转变为MetaBayesianNet。</p>
<p>这里的那个observed或许应该是:</p>
<pre class="line-numbers language-python" data-language="python"><code class="language-python">bn <span class="token operator">=</span> zs<span class="token punctuation">.</span>BayesianNet<span class="token punctuation">(</span>observed<span class="token operator">=</span><span class="token punctuation">&#123;</span><span class="token string">"w_obs"</span><span class="token punctuation">:</span> w<span class="token punctuation">&#125;</span><span class="token punctuation">)</span><span aria-hidden="true" class="line-numbers-rows"><span></span></span></code></pre>

<p>不然写{“w”:w_obs}的话会找不到w_obs报错。</p>
<p>自我否定：这里人家写的没错！</p>
<p>​    这里的w_obs应该是个自定义的张量，通过把它传递过来对贝叶斯net进行不同的训练。也就是说可以吧贝叶斯网络中的w节点也作为一个参数。</p>
<p>​    应该先自定义一个w_obs传过来。</p>
<blockquote>
<p>到目前为止，我们知道如何构建模型并将其重用于不同的观察结果。 构建完成后，BayesianNet支持查询网络当前状态，例如：</p>
<pre class="line-numbers language-python" data-language="python"><code class="language-python"><span class="token operator">></span><span class="token comment"># get named node(s)    获取节点名称</span>
<span class="token operator">></span>w <span class="token operator">=</span> bn<span class="token punctuation">[</span><span class="token string">"w"</span><span class="token punctuation">]</span>
<span class="token operator">></span>w<span class="token punctuation">,</span> y <span class="token operator">=</span> bn<span class="token punctuation">.</span>get<span class="token punctuation">(</span><span class="token punctuation">[</span><span class="token string">"w"</span><span class="token punctuation">,</span> <span class="token string">"y"</span><span class="token punctuation">]</span><span class="token punctuation">)</span>

<span class="token operator">></span><span class="token comment"># get log probabilities of stochastic nodes conditioned on the current</span>
<span class="token operator">></span><span class="token comment"># value of other StochasticTensors.</span>
<span class="token operator">></span><span class="token comment"># 以其他Stochastic Tensor的当前值为条件获取随机节点的log对数概率</span>
<span class="token operator">></span>log_pw<span class="token punctuation">,</span> log_py <span class="token operator">=</span> bn<span class="token punctuation">.</span>cond_log_prob<span class="token punctuation">(</span><span class="token punctuation">[</span><span class="token string">"w"</span><span class="token punctuation">,</span> <span class="token string">"y"</span><span class="token punctuation">]</span><span class="token punctuation">)</span>

<span class="token operator">></span><span class="token comment"># get log joint probability given the current values of all stochastic</span>
<span class="token operator">></span><span class="token comment"># nodes</span>
<span class="token operator">></span><span class="token comment"># 给定所有随机节点的当前值，获得对数联合概率</span>
<span class="token operator">></span>log_joint_value <span class="token operator">=</span> bn<span class="token punctuation">.</span>log_joint<span class="token punctuation">(</span><span class="token punctuation">)</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>

<p>默认情况下，对数联合概率是通过对所有随机节点上的条件对数概率求和而得出的。 这就要求所有随机节点的分配批处理形状正确对齐。  如果不是，则返回值可以是任意的。 大多数时候，您可以调整随机节点的group_ndims参数来解决此问题。  如果不是这种情况，我们仍然可以通过在MetaBayesianNet实例中重写它来自定义对数联合概率函数，如下所示：</p>
<pre class="line-numbers language-python" data-language="python"><code class="language-python"><span class="token operator">></span>meta_bn <span class="token operator">=</span> build_linear_regression<span class="token punctuation">(</span>x<span class="token punctuation">,</span> alpha<span class="token punctuation">,</span> beta<span class="token punctuation">)</span>

<span class="token operator">></span><span class="token keyword">def</span> customized_log_joint<span class="token punctuation">(</span>bn<span class="token punctuation">)</span><span class="token punctuation">:</span>
   <span class="token keyword">return</span> tf<span class="token punctuation">.</span>reduce_sum<span class="token punctuation">(</span>
       bn<span class="token punctuation">.</span>cond_log_prob<span class="token punctuation">(</span><span class="token string">"w"</span><span class="token punctuation">)</span><span class="token punctuation">,</span> axis<span class="token operator">=</span><span class="token operator">-</span><span class="token number">1</span><span class="token punctuation">)</span> <span class="token operator">+</span> bn<span class="token punctuation">.</span>cond_log_prob<span class="token punctuation">(</span><span class="token string">"y"</span><span class="token punctuation">)</span>

<span class="token operator">></span>meta_bn<span class="token punctuation">.</span>log_joint <span class="token operator">=</span> customized_log_joint<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>

<p>然后，由这个meta_bn构建的所有BayesianNet实例将使用所提供的自定义函数来计算bn.log_joint()的结果。</p>
</blockquote>
<h3 id="cond-log-prob-函数"><a href="#cond-log-prob-函数" class="headerlink" title="cond_log_prob()函数"></a><code>cond_log_prob()</code>函数</h3><p> <code>cond_log_prob</code>(<em>name_or_names</em>)</p>
<p>The conditional log probabilities of stochastic nodes, evaluated at their current values (given by <a target="_blank" rel="noopener" href="https://zhusuan.readthedocs.io/en/latest/api/zhusuan.framework.html#zhusuan.framework.bn.StochasticTensor.tensor"><code>StochasticTensor.tensor</code></a>).</p>
<p>随机节点的条件对数概率，按其当前值计算( 由StochasticTensor.tensor给出 )。</p>
<pre class="line-numbers language-python" data-language="python"><code class="language-python">Parameters<span class="token punctuation">:</span>	name_or_names – A string <span class="token keyword">or</span> a <span class="token builtin">list</span> of strings<span class="token punctuation">.</span> Name<span class="token punctuation">(</span>s<span class="token punctuation">)</span> of the stochastic nodes<span class="token punctuation">.</span>

Returns<span class="token punctuation">:</span>	A Tensor <span class="token keyword">or</span> a <span class="token builtin">list</span> of Tensors<span class="token punctuation">.</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span></span></code></pre>



<h3 id="log-joint-函数"><a href="#log-joint-函数" class="headerlink" title="log_joint()函数"></a><code>log_joint()</code>函数</h3><p><code>log_joint</code>()</p>
<p>The default log joint probability of this <a target="_blank" rel="noopener" href="https://zhusuan.readthedocs.io/en/latest/api/zhusuan.framework.html#zhusuan.framework.bn.BayesianNet"><code>BayesianNet</code></a>. It works by summing over all the conditional log probabilities of stochastic nodes evaluated at their current values (samples or observations).</p>
<p>该贝叶斯网络的默认对数联合概率。 它以随机节点当前值（sample或者是observations)的所有条件对数概率相加的方式来得到最终结果。</p>
<pre class="line-numbers language-python" data-language="python"><code class="language-python">Returns<span class="token punctuation">:</span> A Tensor<span class="token punctuation">.</span><span aria-hidden="true" class="line-numbers-rows"><span></span></span></code></pre>

<h4 id="补充：字典"><a href="#补充：字典" class="headerlink" title="补充：字典"></a>补充：字典</h4><p>​    字典是另一种可变容器模型，且可存储任意类型对象。</p>
<p>​    字典的每个键值 key=&gt;value 对用冒号 : 分割，每个键值对之间用逗号 , 分割，整个字典包括在花括号 {} 中 ,格式如下所示： </p>
<pre class="line-numbers language-python" data-language="python"><code class="language-python">d <span class="token operator">=</span> <span class="token punctuation">&#123;</span>key1 <span class="token punctuation">:</span> value1<span class="token punctuation">,</span> key2 <span class="token punctuation">:</span> value2 <span class="token punctuation">&#125;</span><span aria-hidden="true" class="line-numbers-rows"><span></span></span></code></pre>

<p>​    值可以取任何数据类型，但键必须是不可变的，如字符串，数字或元组。</p>
<p>​    一个简单的字典实例：</p>
<pre class="line-numbers language-python" data-language="python"><code class="language-python"><span class="token builtin">dict</span> <span class="token operator">=</span> <span class="token punctuation">&#123;</span><span class="token string">'Alice'</span><span class="token punctuation">:</span> <span class="token string">'2341'</span><span class="token punctuation">,</span> <span class="token string">'Beth'</span><span class="token punctuation">:</span> <span class="token string">'9102'</span><span class="token punctuation">,</span> <span class="token string">'Cecil'</span><span class="token punctuation">:</span> <span class="token string">'3258'</span><span class="token punctuation">&#125;</span><span aria-hidden="true" class="line-numbers-rows"><span></span></span></code></pre>

<p>​    也可如此创建字典：</p>
<pre class="line-numbers language-python" data-language="python"><code class="language-python">dict1 <span class="token operator">=</span> <span class="token punctuation">&#123;</span> <span class="token string">'abc'</span><span class="token punctuation">:</span> <span class="token number">456</span> <span class="token punctuation">&#125;</span> 
dict2 <span class="token operator">=</span> <span class="token punctuation">&#123;</span> <span class="token string">'abc'</span><span class="token punctuation">:</span> <span class="token number">123</span><span class="token punctuation">,</span> <span class="token number">98.6</span><span class="token punctuation">:</span> <span class="token number">37</span> <span class="token punctuation">&#125;</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span></span></code></pre>

<ul>
<li>参考：<a target="_blank" rel="noopener" href="https://www.runoob.com/python/python-dictionary.html">菜鸟教程：字典</a></li>
</ul>
<h4 id="补充：函数装饰器"><a href="#补充：函数装饰器" class="headerlink" title="补充：函数装饰器"></a>补充：函数装饰器</h4><p>Python中的函数装饰器，写法注解一样。。。 所谓的装饰器，就是通过装饰器函数，来修改原函数的一些功能，使得原函数不需要修改。 </p>
<p>详细见：<a target="_blank" rel="noopener" href="http://c.biancheng.net/view/2270.html">Python@函数装饰器及其用法</a></p>
<h4 id="补充：惰性函数"><a href="#补充：惰性函数" class="headerlink" title="补充：惰性函数"></a>补充：惰性函数</h4><p>惰性函数好像是js中的一个概念？</p>
<p>具体讲解：<a target="_blank" rel="noopener" href="https://blog.csdn.net/orchid_djl/article/details/79955021">JS高阶-惰性函数</a></p>
<p>JS惰性函数，是针对优化频繁使用的函数。常用于函数库的编写、单例模式之中。</p>
<p> 惰性载入表示函数执行的分支只会在函数第一次掉用的时候执行，在第一次调用过程中，该函数会被覆盖为另一个按照合适方式执行的函数，这样任何对原函数的调用就不用再经过执行的分支了。 </p>
<h4 id="补充：贝叶斯线性回归"><a href="#补充：贝叶斯线性回归" class="headerlink" title="补充：贝叶斯线性回归"></a>补充：贝叶斯线性回归</h4><p>x为自变量，输入值；  y为输出值。</p>
<ol>
<li>频率派线性回归：y = ax + b（一元）</li>
</ol>
<p>​       <strong>y</strong>=<strong>β^T X</strong>+<strong>ω</strong> （多元，其中的各项均为向量）</p>
<ol start="2">
<li>贝叶斯线性回归：y ~ N(<strong>w</strong>^t <strong>x</strong>,β^2)</li>
</ol>
<p>​        其中的各项变量应该为分布</p>

                
            </div>
            <hr/>

            

    <div class="reprint" id="reprint-statement">
        
            <div class="reprint__author">
                <span class="reprint-meta" style="font-weight: bold;">
                    <i class="fas fa-user">
                        文章作者:
                    </i>
                </span>
                <span class="reprint-info">
                    <a href="/about" rel="external nofollow noreferrer">SongX64</a>
                </span>
            </div>
            <div class="reprint__type">
                <span class="reprint-meta" style="font-weight: bold;">
                    <i class="fas fa-link">
                        文章链接:
                    </i>
                </span>
                <span class="reprint-info">
                    <a href="https://songx86.gitee.io/article/d7c4fee9.html">https://songx86.gitee.io/article/d7c4fee9.html</a>
                </span>
            </div>
            <div class="reprint__notice">
                <span class="reprint-meta" style="font-weight: bold;">
                    <i class="fas fa-copyright">
                        版权声明:
                    </i>
                </span>
                <span class="reprint-info">
                    本博客所有文章除特別声明外，均采用
                    <a href="https://creativecommons.org/licenses/by/4.0/deed.zh" rel="external nofollow noreferrer" target="_blank">CC BY 4.0</a>
                    许可协议。转载请注明来源
                    <a href="/about" target="_blank">SongX64</a>
                    !
                </span>
            </div>
        
    </div>

    <script async defer>
      document.addEventListener("copy", function (e) {
        let toastHTML = '<span>复制成功，请遵循本文的转载规则</span><button class="btn-flat toast-action" onclick="navToReprintStatement()" style="font-size: smaller">查看</a>';
        M.toast({html: toastHTML})
      });

      function navToReprintStatement() {
        $("html, body").animate({scrollTop: $("#reprint-statement").offset().top - 80}, 800);
      }
    </script>



            <div class="tag_share" style="display: block;">
                <div class="post-meta__tag-list" style="display: inline-block;">
                    
                        <div class="article-tag">
                            
                                <a href="/tags/%E7%A7%91%E7%A0%94/">
                                    <span class="chip bg-color">科研</span>
                                </a>
                            
                                <a href="/tags/%E7%8F%A0%E7%AE%97/">
                                    <span class="chip bg-color">珠算</span>
                                </a>
                            
                        </div>
                    
                </div>
                <div class="post_share" style="zoom: 80%; width: fit-content; display: inline-block; float: right; margin: -0.15rem 0;">
                    <link rel="stylesheet" type="text/css" href="/libs/share/css/share.min.css">
<div id="article-share">

    
    <div class="social-share" data-sites="twitter,facebook,google,qq,qzone,wechat,weibo,douban,linkedin" data-wechat-qrcode-helper="<p>微信扫一扫即可分享！</p>"></div>
    <script src="/libs/share/js/social-share.min.js"></script>
    

    

</div>

                </div>
            </div>
            
                <style>
    #reward {
        margin: 40px 0;
        text-align: center;
    }

    #reward .reward-link {
        font-size: 1.4rem;
        line-height: 38px;
    }

    #reward .btn-floating:hover {
        box-shadow: 0 6px 12px rgba(0, 0, 0, 0.2), 0 5px 15px rgba(0, 0, 0, 0.2);
    }

    #rewardModal {
        width: 320px;
        height: 350px;
    }

    #rewardModal .reward-title {
        margin: 15px auto;
        padding-bottom: 5px;
    }

    #rewardModal .modal-content {
        padding: 10px;
    }

    #rewardModal .close {
        position: absolute;
        right: 15px;
        top: 15px;
        color: rgba(0, 0, 0, 0.5);
        font-size: 1.3rem;
        line-height: 20px;
        cursor: pointer;
    }

    #rewardModal .close:hover {
        color: #ef5350;
        transform: scale(1.3);
        -moz-transform:scale(1.3);
        -webkit-transform:scale(1.3);
        -o-transform:scale(1.3);
    }

    #rewardModal .reward-tabs {
        margin: 0 auto;
        width: 210px;
    }

    .reward-tabs .tabs {
        height: 38px;
        margin: 10px auto;
        padding-left: 0;
    }

    .reward-content ul {
        padding-left: 0 !important;
    }

    .reward-tabs .tabs .tab {
        height: 38px;
        line-height: 38px;
    }

    .reward-tabs .tab a {
        color: #fff;
        background-color: #ccc;
    }

    .reward-tabs .tab a:hover {
        background-color: #ccc;
        color: #fff;
    }

    .reward-tabs .wechat-tab .active {
        color: #fff !important;
        background-color: #22AB38 !important;
    }

    .reward-tabs .alipay-tab .active {
        color: #fff !important;
        background-color: #019FE8 !important;
    }

    .reward-tabs .reward-img {
        width: 210px;
        height: 210px;
    }
</style>

<div id="reward">
    <a href="#rewardModal" class="reward-link modal-trigger btn-floating btn-medium waves-effect waves-light red">赏</a>

    <!-- Modal Structure -->
    <div id="rewardModal" class="modal">
        <div class="modal-content">
            <a class="close modal-close"><i class="fas fa-times"></i></a>
            <h4 class="reward-title">你的赏识是我前进的动力</h4>
            <div class="reward-content">
                <div class="reward-tabs">
                    <ul class="tabs row">
                        <li class="tab col s6 alipay-tab waves-effect waves-light"><a href="#alipay">支付宝</a></li>
                        <li class="tab col s6 wechat-tab waves-effect waves-light"><a href="#wechat">微 信</a></li>
                    </ul>
                    <div id="alipay">
                        <img src="/medias/reward/alipay.jpg" class="reward-img" alt="支付宝打赏二维码">
                    </div>
                    <div id="wechat">
                        <img src="/medias/reward/wechat.jpg" class="reward-img" alt="微信打赏二维码">
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

<script>
    $(function () {
        $('.tabs').tabs();
    });
</script>

            
        </div>
    </div>

    

    

    

    

    
        <style>
    .valine-card {
        margin: 1.5rem auto;
    }

    .valine-card .card-content {
        padding: 20px 20px 5px 20px;
    }

    #vcomments textarea {
        box-sizing: border-box;
        background: url("/medias/comment_bg.png") 100% 100% no-repeat;
    }

    #vcomments p {
        margin: 2px 2px 10px;
        font-size: 1.05rem;
        line-height: 1.78rem;
    }

    #vcomments blockquote p {
        text-indent: 0.2rem;
    }

    #vcomments a {
        padding: 0 2px;
        color: #4cbf30;
        font-weight: 500;
        text-decoration: none;
    }

    #vcomments img {
        max-width: 100%;
        height: auto;
        cursor: pointer;
    }

    #vcomments ol li {
        list-style-type: decimal;
    }

    #vcomments ol,
    ul {
        display: block;
        padding-left: 2em;
        word-spacing: 0.05rem;
    }

    #vcomments ul li,
    ol li {
        display: list-item;
        line-height: 1.8rem;
        font-size: 1rem;
    }

    #vcomments ul li {
        list-style-type: disc;
    }

    #vcomments ul ul li {
        list-style-type: circle;
    }

    #vcomments table, th, td {
        padding: 12px 13px;
        border: 1px solid #dfe2e5;
    }

    #vcomments table, th, td {
        border: 0;
    }

    table tr:nth-child(2n), thead {
        background-color: #fafafa;
    }

    #vcomments table th {
        background-color: #f2f2f2;
        min-width: 80px;
    }

    #vcomments table td {
        min-width: 80px;
    }

    #vcomments h1 {
        font-size: 1.85rem;
        font-weight: bold;
        line-height: 2.2rem;
    }

    #vcomments h2 {
        font-size: 1.65rem;
        font-weight: bold;
        line-height: 1.9rem;
    }

    #vcomments h3 {
        font-size: 1.45rem;
        font-weight: bold;
        line-height: 1.7rem;
    }

    #vcomments h4 {
        font-size: 1.25rem;
        font-weight: bold;
        line-height: 1.5rem;
    }

    #vcomments h5 {
        font-size: 1.1rem;
        font-weight: bold;
        line-height: 1.4rem;
    }

    #vcomments h6 {
        font-size: 1rem;
        line-height: 1.3rem;
    }

    #vcomments p {
        font-size: 1rem;
        line-height: 1.5rem;
    }

    #vcomments hr {
        margin: 12px 0;
        border: 0;
        border-top: 1px solid #ccc;
    }

    #vcomments blockquote {
        margin: 15px 0;
        border-left: 5px solid #42b983;
        padding: 1rem 0.8rem 0.3rem 0.8rem;
        color: #666;
        background-color: rgba(66, 185, 131, .1);
    }

    #vcomments pre {
        font-family: monospace, monospace;
        padding: 1.2em;
        margin: .5em 0;
        background: #272822;
        overflow: auto;
        border-radius: 0.3em;
        tab-size: 4;
    }

    #vcomments code {
        font-family: monospace, monospace;
        padding: 1px 3px;
        font-size: 0.92rem;
        color: #e96900;
        background-color: #f8f8f8;
        border-radius: 2px;
    }

    #vcomments pre code {
        font-family: monospace, monospace;
        padding: 0;
        color: #e8eaf6;
        background-color: #272822;
    }

    #vcomments pre[class*="language-"] {
        padding: 1.2em;
        margin: .5em 0;
    }

    #vcomments code[class*="language-"],
    pre[class*="language-"] {
        color: #e8eaf6;
    }

    #vcomments [type="checkbox"]:not(:checked), [type="checkbox"]:checked {
        position: inherit;
        margin-left: -1.3rem;
        margin-right: 0.4rem;
        margin-top: -1px;
        vertical-align: middle;
        left: unset;
        visibility: visible;
    }

    #vcomments b,
    strong {
        font-weight: bold;
    }

    #vcomments dfn {
        font-style: italic;
    }

    #vcomments small {
        font-size: 85%;
    }

    #vcomments cite {
        font-style: normal;
    }

    #vcomments mark {
        background-color: #fcf8e3;
        padding: .2em;
    }

    #vcomments table, th, td {
        padding: 12px 13px;
        border: 1px solid #dfe2e5;
    }

    table tr:nth-child(2n), thead {
        background-color: #fafafa;
    }

    #vcomments table th {
        background-color: #f2f2f2;
        min-width: 80px;
    }

    #vcomments table td {
        min-width: 80px;
    }

    #vcomments [type="checkbox"]:not(:checked), [type="checkbox"]:checked {
        position: inherit;
        margin-left: -1.3rem;
        margin-right: 0.4rem;
        margin-top: -1px;
        vertical-align: middle;
        left: unset;
        visibility: visible;
    }
</style>

<div class="card valine-card" data-aos="fade-up">
    <div class="comment_headling" style="font-size: 20px; font-weight: 700; position: relative; padding-left: 20px; top: 15px; padding-bottom: 5px;">
        <i class="fas fa-comments fa-fw" aria-hidden="true"></i>
        <span>评论</span>
    </div>
    <div id="vcomments" class="card-content" style="display: grid">
    </div>
</div>

<script src="/libs/valine/av-min.js"></script>
<script src="/libs/valine/Valine.min.js"></script>
<script>
    new Valine({
        el: '#vcomments',
        appId: 'gRuzkj3uDnUjERvWlFkWkYjF-gzGzoHsz',
        appKey: 'tCCMKQDflcsl0hOAh2CUfvPP',
        notify: 'false' === 'true',
        verify: 'false' === 'true',
        visitor: 'true' === 'true',
        avatar: 'mm',
        pageSize: '10',
        lang: 'zh-cn',
        placeholder: 'just go go'
    });
</script>

<!--酷Q推送-->


    

    

    

    

    

<article id="prenext-posts" class="prev-next articles">
    <div class="row article-row">
        
        <div class="article col s12 m6" data-aos="fade-up">
            <div class="article-badge left-badge text-color">
                <i class="fas fa-chevron-left"></i>&nbsp;上一篇</div>
            <div class="card">
                <a href="/article/907c87e0.html">
                    <div class="card-image">
                        
                        
                        <img src="/medias/featureimages/1/04.jpg" class="responsive-img" alt="SpringBoot创建项目">
                        
                        <span class="card-title">SpringBoot创建项目</span>
                    </div>
                </a>
                <div class="card-content article-content">
                    <div class="summary block-with-text">
                        
                            SpringBoot创建项目,并整合一些常用组件。记录了其过程以及其中遇到的错误。还有一些基本注解的解释。
                        
                    </div>
                    <div class="publish-info">
                        <span class="publish-date">
                            <i class="far fa-clock fa-fw icon-date"></i>2020-03-12
                        </span>
                        <span class="publish-author">
                            
                            <i class="fas fa-bookmark fa-fw icon-category"></i>
                            
                            <a href="/categories/%E5%90%8E%E7%AB%AF/" class="post-category">
                                    后端
                                </a>
                            
                            
                        </span>
                    </div>
                </div>
                
                <div class="card-action article-tags">
                    
                    <a href="/tags/Java/">
                        <span class="chip bg-color">Java</span>
                    </a>
                    
                    <a href="/tags/Springboot/">
                        <span class="chip bg-color">Springboot</span>
                    </a>
                    
                    <a href="/tags/%E5%B8%B8%E7%94%A8%E7%BB%84%E4%BB%B6/">
                        <span class="chip bg-color">常用组件</span>
                    </a>
                    
                </div>
                
            </div>
        </div>
        
        
        <div class="article col s12 m6" data-aos="fade-up">
            <div class="article-badge right-badge text-color">
                下一篇&nbsp;<i class="fas fa-chevron-right"></i>
            </div>
            <div class="card">
                <a href="/article/67e1287c.html">
                    <div class="card-image">
                        
                        
                        <img src="/medias/featureimages/1/04.jpg" class="responsive-img" alt="Hello,Hexo——关于Hexo部署CSS样式出错的解决">
                        
                        <span class="card-title">Hello,Hexo——关于Hexo部署CSS样式出错的解决</span>
                    </div>
                </a>
                <div class="card-content article-content">
                    <div class="summary block-with-text">
                        
                            搭建Hexo博客后的第一篇尝试
                        
                    </div>
                    <div class="publish-info">
                            <span class="publish-date">
                                <i class="far fa-clock fa-fw icon-date"></i>2020-01-15
                            </span>
                        <span class="publish-author">
                            
                            <i class="fas fa-bookmark fa-fw icon-category"></i>
                            
                            <a href="/categories/%E6%9D%82%E9%A1%B9/" class="post-category">
                                    杂项
                                </a>
                            
                            
                        </span>
                    </div>
                </div>
                
                <div class="card-action article-tags">
                    
                    <a href="/tags/%E6%9D%82%E9%A1%B9/">
                        <span class="chip bg-color">杂项</span>
                    </a>
                    
                </div>
                
            </div>
        </div>
        
    </div>
</article>

</div>



<!-- 代码块功能依赖 -->
<script type="text/javascript" src="/libs/codeBlock/codeBlockFuction.js"></script>

<!-- 代码语言 -->

<script type="text/javascript" src="/libs/codeBlock/codeLang.js"></script>


<!-- 代码块复制 -->

<script type="text/javascript" src="/libs/codeBlock/codeCopy.js"></script>


<!-- 代码块收缩 -->

<script type="text/javascript" src="/libs/codeBlock/codeShrink.js"></script>


    </div>
    <div id="toc-aside" class="expanded col l3 hide-on-med-and-down">
        <div class="toc-widget card" style="background-color: white;">
            <div class="toc-title"><i class="far fa-list-alt"></i>&nbsp;&nbsp;目录</div>
            <div id="toc-content"></div>
        </div>
    </div>
</div>

<!-- TOC 悬浮按钮. -->

<div id="floating-toc-btn" class="hide-on-med-and-down">
    <a class="btn-floating btn-large bg-color">
        <i class="fas fa-list-ul"></i>
    </a>
</div>


<script src="/libs/tocbot/tocbot.min.js"></script>
<script>
    $(function () {
        tocbot.init({
            tocSelector: '#toc-content',
            contentSelector: '#articleContent',
            headingsOffset: -($(window).height() * 0.4 - 45),
            collapseDepth: Number('0'),
            headingSelector: 'h2, h3, h4'
        });

        // modify the toc link href to support Chinese.
        let i = 0;
        let tocHeading = 'toc-heading-';
        $('#toc-content a').each(function () {
            $(this).attr('href', '#' + tocHeading + (++i));
        });

        // modify the heading title id to support Chinese.
        i = 0;
        $('#articleContent').children('h2, h3, h4').each(function () {
            $(this).attr('id', tocHeading + (++i));
        });

        // Set scroll toc fixed.
        let tocHeight = parseInt($(window).height() * 0.4 - 64);
        let $tocWidget = $('.toc-widget');
        $(window).scroll(function () {
            let scroll = $(window).scrollTop();
            /* add post toc fixed. */
            if (scroll > tocHeight) {
                $tocWidget.addClass('toc-fixed');
            } else {
                $tocWidget.removeClass('toc-fixed');
            }
        });

        
        /* 修复文章卡片 div 的宽度. */
        let fixPostCardWidth = function (srcId, targetId) {
            let srcDiv = $('#' + srcId);
            if (srcDiv.length === 0) {
                return;
            }

            let w = srcDiv.width();
            if (w >= 450) {
                w = w + 21;
            } else if (w >= 350 && w < 450) {
                w = w + 18;
            } else if (w >= 300 && w < 350) {
                w = w + 16;
            } else {
                w = w + 14;
            }
            $('#' + targetId).width(w);
        };

        // 切换TOC目录展开收缩的相关操作.
        const expandedClass = 'expanded';
        let $tocAside = $('#toc-aside');
        let $mainContent = $('#main-content');
        $('#floating-toc-btn .btn-floating').click(function () {
            if ($tocAside.hasClass(expandedClass)) {
                $tocAside.removeClass(expandedClass).hide();
                $mainContent.removeClass('l9');
            } else {
                $tocAside.addClass(expandedClass).show();
                $mainContent.addClass('l9');
            }
            fixPostCardWidth('artDetail', 'prenext-posts');
        });
        
    });
</script>

    

</main>




    <footer class="page-footer bg-color">
    
        <link rel="stylesheet" href="/libs/aplayer/APlayer.min.css">
<style>
    .aplayer .aplayer-lrc p {
        
        display: none;
        
        font-size: 12px;
        font-weight: 700;
        line-height: 16px !important;
    }

    .aplayer .aplayer-lrc p.aplayer-lrc-current {
        
        display: none;
        
        font-size: 15px;
        color: #42b983;
    }

    
    .aplayer.aplayer-fixed.aplayer-narrow .aplayer-body {
        left: -66px !important;
    }

    .aplayer.aplayer-fixed.aplayer-narrow .aplayer-body:hover {
        left: 0px !important;
    }

    
</style>
<div class="">
    
    <div class="row">
        <meting-js class="col l8 offset-l2 m10 offset-m1 s12"
                   server="netease"
                   type="playlist"
                   id="767683882"
                   fixed='true'
                   autoplay='false'
                   theme='#42b983'
                   loop='all'
                   order='random'
                   preload='auto'
                   volume='0.7'
                   list-folded='true'
        >
        </meting-js>
    </div>
</div>

<script src="/libs/aplayer/APlayer.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/meting@2/dist/Meting.min.js"></script>

    
    <div class="container row center-align" style="margin-bottom: 0px !important;">
        <div class="col s12 m8 l8 copy-right">
            Copyright&nbsp;&copy;
            
                <span id="year">2020-2021</span>
            
            <span id="year">2020</span>
            <a href="/about" target="_blank">SongX64</a>
            |&nbsp;Powered by&nbsp;<a href="https://hexo.io/" target="_blank">Hexo</a>
            |&nbsp;Theme&nbsp;<a href="https://github.com/blinkfox/hexo-theme-matery" target="_blank">Matery</a>
			<br>
				<a href="https://beian.miit.gov.cn/" target="_blank">鲁ICP备2021015839号-1</a>
				 | 
				<img src="/medias/icp.png" style="vertical-align: text-bottom;" />
		 		<a target="_blank" href="http://www.beian.gov.cn/portal/registerSystemInfo?recordcode=37083102000087">鲁公网安备 37083102000087号</a>
            </span>
			
		 
            <br>
            
            
            
            
            
            <br>
            
            <br>
            
        </div>
        <div class="col s12 m4 l4 social-link ">
    <a href="https://github.com/SongX64" class="tooltipped" target="_blank" data-tooltip="访问我的GitHub" data-position="top" data-delay="50">
        <i class="fab fa-github"></i>
    </a>



    <a href="mailto:song.x64@gmail.com" class="tooltipped" target="_blank" data-tooltip="邮件联系我" data-position="top" data-delay="50">
        <i class="fas fa-envelope-open"></i>
    </a>







    <a href="tencent://AddContact/?fromId=50&fromSubId=1&subcmd=all&uin=song-x64@qq.com" class="tooltipped" target="_blank" data-tooltip="QQ联系我: song-x64@qq.com" data-position="top" data-delay="50">
        <i class="fab fa-qq"></i>
    </a>







</div>
    </div>
</footer>

<div class="progress-bar"></div>


    <!-- 搜索遮罩框 -->
<div id="searchModal" class="modal">
    <div class="modal-content">
        <div class="search-header">
            <span class="title"><i class="fas fa-search"></i>&nbsp;&nbsp;搜索</span>
            <input type="search" id="searchInput" name="s" placeholder="请输入搜索的关键字"
                   class="search-input">
        </div>
        <div id="searchResult"></div>
    </div>
</div>

<script type="text/javascript">
$(function () {
    var searchFunc = function (path, search_id, content_id) {
        'use strict';
        $.ajax({
            url: path,
            dataType: "xml",
            success: function (xmlResponse) {
                // get the contents from search data
                var datas = $("entry", xmlResponse).map(function () {
                    return {
                        title: $("title", this).text(),
                        content: $("content", this).text(),
                        url: $("url", this).text()
                    };
                }).get();
                var $input = document.getElementById(search_id);
                var $resultContent = document.getElementById(content_id);
                $input.addEventListener('input', function () {
                    var str = '<ul class=\"search-result-list\">';
                    var keywords = this.value.trim().toLowerCase().split(/[\s\-]+/);
                    $resultContent.innerHTML = "";
                    if (this.value.trim().length <= 0) {
                        return;
                    }
                    // perform local searching
                    datas.forEach(function (data) {
                        var isMatch = true;
                        var data_title = data.title.trim().toLowerCase();
                        var data_content = data.content.trim().replace(/<[^>]+>/g, "").toLowerCase();
                        var data_url = data.url;
                        data_url = data_url.indexOf('/') === 0 ? data.url : '/' + data_url;
                        var index_title = -1;
                        var index_content = -1;
                        var first_occur = -1;
                        // only match artiles with not empty titles and contents
                        if (data_title !== '' && data_content !== '') {
                            keywords.forEach(function (keyword, i) {
                                index_title = data_title.indexOf(keyword);
                                index_content = data_content.indexOf(keyword);
                                if (index_title < 0 && index_content < 0) {
                                    isMatch = false;
                                } else {
                                    if (index_content < 0) {
                                        index_content = 0;
                                    }
                                    if (i === 0) {
                                        first_occur = index_content;
                                    }
                                }
                            });
                        }
                        // show search results
                        if (isMatch) {
                            str += "<li><a href='" + data_url + "' class='search-result-title'>" + data_title + "</a>";
                            var content = data.content.trim().replace(/<[^>]+>/g, "");
                            if (first_occur >= 0) {
                                // cut out 100 characters
                                var start = first_occur - 20;
                                var end = first_occur + 80;
                                if (start < 0) {
                                    start = 0;
                                }
                                if (start === 0) {
                                    end = 100;
                                }
                                if (end > content.length) {
                                    end = content.length;
                                }
                                var match_content = content.substr(start, end);
                                // highlight all keywords
                                keywords.forEach(function (keyword) {
                                    var regS = new RegExp(keyword, "gi");
                                    match_content = match_content.replace(regS, "<em class=\"search-keyword\">" + keyword + "</em>");
                                });

                                str += "<p class=\"search-result\">" + match_content + "...</p>"
                            }
                            str += "</li>";
                        }
                    });
                    str += "</ul>";
                    $resultContent.innerHTML = str;
                });
            }
        });
    };

    searchFunc('/search.xml', 'searchInput', 'searchResult');
});
</script>

    <!-- 回到顶部按钮 -->
<div id="backTop" class="top-scroll">
    <a class="btn-floating btn-large waves-effect waves-light" href="#!">
        <i class="fas fa-arrow-up"></i>
    </a>
</div>


    <script src="/libs/materialize/materialize.min.js"></script>
    <script src="/libs/masonry/masonry.pkgd.min.js"></script>
    <script src="/libs/aos/aos.js"></script>
    <script src="/libs/scrollprogress/scrollProgress.min.js"></script>
    <script src="/libs/lightGallery/js/lightgallery-all.min.js"></script>
    <script src="/js/matery.js"></script>

    <!-- Baidu Analytics -->

    <!-- Baidu Push -->

<script>
    (function () {
        var bp = document.createElement('script');
        var curProtocol = window.location.protocol.split(':')[0];
        if (curProtocol === 'https') {
            bp.src = 'https://zz.bdstatic.com/linksubmit/push.js';
        } else {
            bp.src = 'http://push.zhanzhang.baidu.com/push.js';
        }
        var s = document.getElementsByTagName("script")[0];
        s.parentNode.insertBefore(bp, s);
    })();
</script>

    
    <script src="/libs/others/clicklove.js" async="async"></script>
    
    

    

    

    <!--腾讯兔小巢-->
    
        <div style="position:fixed;bottom:125px;right:16px;cursor: pointer;">
            <a title="兔小巢" target="_blank" rel="noopener" href="https://support.qq.com/products/330452"><i class="fa fa-comments fa-3x"  aria-hidden="true"></i></a>
        </div>
    
    
    <script type="text/javascript" color="0,0,255"
        pointColor="0,0,255" opacity='0.5'
        zIndex="-1" count="99"
        src="/libs/background/canvas-nest.js"></script>
    

    

    
    <script type="text/javascript" src="/libs/background/ribbon-dynamic.js" async="async"></script>
    

    
    <script src="/libs/instantpage/instantpage.js" type="module"></script>
    

<script src="/live2dw/lib/L2Dwidget.min.js?094cbace49a39548bed64abff5988b05"></script><script>L2Dwidget.init({"pluginRootPath":"live2dw/","pluginJsPath":"lib/","pluginModelPath":"assets/","tagMode":false,"log":false,"model":{"jsonPath":"/live2dw/assets/shizuku.model.json"},"display":{"position":"right","width":150,"height":300},"mobile":{"show":true},"react":{"opacity":0.7}});</script></body>

</html>
